【问题标题】:How to hide and show divs on button click created dynamically in Vuejs如何在 Vuejs 中动态创建的按钮单击时隐藏和显示 div
【发布时间】:2020-04-09 15:11:19
【问题描述】:

我已经动态创建了按钮和 div,我想在点击相关按钮时显示 div 并隐藏其余部分。我不知道计数,因为它们是动态创建的。在vue js中怎么做?

<div style="margin-left: -88px;margin-top: 20px;">

<button v-for="namelock in tour_location"  style="background-color:#EFF5FA;border: 0;border-radius: 15px;font-size: 14px;margin-left: 60px;">{{namelock.name}}</button>



<div v-for="(location,index ) in tour_location">

<h1>My Dynamic data</h1></div>

【问题讨论】:

  • 你能告诉我们你到目前为止做了什么吗?
  • 我在我的问题中添加了代码,我之前尝试过 v-if 但为此我必须首先初始化我不想要的变量,因为这些数据是动态的
  • 您能告诉我们您在v-for 中使用的数组示例吗?以及何时显示按钮的条件
  • 我只是点击什么按钮,相关的 div 应该显示在标签菜单中

标签: vue.js vuejs2 vue-component vuex vuetify.js


【解决方案1】:

您可以使用v-show,将 show prop @click 更改为您要显示的对象的 id,然后在 v-show 上您可以检查 show prop 是否等于您要显示的对象 id

<div id="app">
  <button v-for="b in buttons" @click='show = b' class="btn m-4 btn-primary">{{b}}</button>
  <div class="container">
    <div class="row">
      <div v-show="show === d.id" v-for='d in divs' class="col-sm-3 m-2">
        {{d.name}}
      </div>
    </div>
  </div>
</div>

然后在vue脚本中

var app = new Vue({
  el: '#app',
  data: {
    buttons: [1,2,3],
    divs: [{id:1,name:'apple'},{id:2,name:'mango'},{id:3,name:'banana'}],
    show: null
  },
})

继承人的工作代码 Code pen

【讨论】:

  • 嘿,谢谢您的回答,还有一件事:我们如何让第一个 div 默认处于活动状态,因为现在我需要在第一次加载页面时先单击以显示 div。
  • 嗯,你可以将 show prop 更改为第一个对象的 id 而不是 null 以默认显示它。 show: 1
猜你喜欢
  • 1970-01-01
  • 2016-05-21
  • 2013-04-24
  • 2013-01-16
  • 1970-01-01
  • 2018-03-17
  • 1970-01-01
  • 2021-06-14
  • 2017-11-25
相关资源
最近更新 更多