renlu90
renlu90

Reputation: 1

v-show inside a v-for loop, i need to open only the clicked option

I just started learning Vue.js and I need some help. I have a v-show within a v-for loop set up, there is a show button within the loop, when I click this, at the moment it opens all the hidden divs, I want it to open only the relevant one that's clicked. Maybe there is another way to do this or a better way I have been reading that v-show might not be suited to be used inside a loop.

    <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>

Thanks in advance for the help.

Upvotes: 0

Views: 221

Answers (1)

Larizza Tueros
Larizza Tueros

Reputation: 629

The problem is you are tracking the active changes with only one variable active but you need to track each item, so you have two options add an active property to each item object or track the active item in an array. I'm going to show you the first

// 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>

Note: If you only want to change the div styles you can do it with a bind class.

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

Upvotes: 1

Related Questions