【问题标题】:v-show inside a v-for loop, i need to open only the clicked optionv-show 在 v-for 循环中,我只需要打开单击的选项
【发布时间】:2021-06-18 16:11:15
【问题描述】:

我刚开始学习 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>

提前感谢您的帮助。

【问题讨论】:

    标签: javascript jquery arrays vue.js frontend


    【解决方案1】:

    问题是您仅使用一个变量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>
    

    【讨论】:

      猜你喜欢
      • 2019-08-20
      • 2018-02-01
      • 1970-01-01
      • 2021-10-05
      • 1970-01-01
      • 2021-02-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多