首页 > 解决方案 > v-show 在 v-for 循环中,我只需要打开单击的选项

问题描述

我刚开始学习 Vue.js,我需要一些帮助。我在 v-for 循环中设置了一个 v-show,循环中有一个显示按钮,当我点击它时,它会打开所有隐藏的 div,我希望它只打开被点击的相关的. 也许有另一种方法可以做到这一点,或者我一直在阅读的更好的方法 v-show 可能不适合在循环中使用。

    <style>
      * {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
    font-family: "Montserrat", sans-serif;
  }
    
  .content {
    width: 100px;
    height: 100px;
    background-color: red;
  }
  
  .contenttwo {
    width: 50px;
    height: 50px;
    background-color: green;
  }
    </style>
</head>

<body>

    <div  id="root">

        <div  v-for="item in dropdownVoices" :key="item.voice"   class="">

          <div v-show="active" class="content">
    
          </div>
    
          <div v-show="!active" class="contenttwo">
    
          </div>
    
          <button type="button" name="button" v-on:click="active = !active">Change me</button>
        </div>

      </div>
    
    <script  charset="utf-8">
        var app = new Vue({
    el: '#root',
    data: {
      active:true,
      dropdownVoices:[
     { voice: 'One' },
     { voice: 'Two' },
     { voice: 'Three' },
     { voice: 'Four' },
     { voice: 'Five' },
     { voice: 'Six' }
   ],
    },
    method:{
   
    }
   });
   Vue.config.devtools = true;

    </script>
</body>
</html>

在此先感谢您的帮助。

标签: javascriptjqueryarraysvue.jsfrontend

解决方案


问题是您仅使用一个变量来跟踪活动更改,active但您需要跟踪每个项目,因此您有两个选项可以为每个项目对象添加一个活动属性或跟踪数组中的活动项目。我要给你看第一个

// script
data: {
  dropdownVoices:[
    { voice: 'One' , active: true},
    { voice: 'Two' , active: true},
    { voice: 'Three' , active: true},
    { voice: 'Four' , active: true},
    { voice: 'Five' , active: true},
    { voice: 'Six', active: true }
  ],
}

// template 
<div  v-for="item in dropdownVoices" :key="item.voice" class="">
  <div v-show="item.active" class="content"></div>    
  <div v-show="!item.active" class="contenttwo"></div>
  <button type="button" name="button" v-on:click="item.active = !item.active">Change me</button>
</div>

注意:如果您只想更改 div 样式,可以使用绑定类来完成。

<div :class="item.active ? 'content' : 'contenttwo'"></div>

推荐阅读