Skip to content
Advertisement

Show and hide certain divs inside of v-for loop based on their value?

I have a list of objects that are being shown in a v-for loop. They all have a certain key value pair, and based upon that value I’d like for the user to be able to toggle a button outside the loop structure to either show or hide those elements. Basically I want all of the items to be shown at first, and then once the button is toggled, only the items with the true value to be shown, then back to all items, etc.

Something like

 const items = [
    { 
      exampleKey: false
    },
    { 
      exampleKey: true
    },
    { 
      exampleKey: false
    }
 ]

 <button @click="updateList">click to update list</div>
 <div v-for="items in itemList">item example</div>

 methods: {
    updateList: function(){
        // make the magic happen
    }
 }

Of course this is just some pseudo code but it illustrates what I’m trying to get at. I am looking for some type of method or computed property that will let the user toggle the items visibility.

Advertisement

Answer

So you shouldn’t combine v-for and v-if on the same element. What you can do is either include a filter in your v-for:

<div v-for="item in items.filter(i => i.exampleKey)">{{item.foo}}</div>

Or (my preference) you can iterate items as normal to create container divs, and add child content only where the desired condition is satisfied:

<div v-for="item in items">
  <div v-if="item.exampleKey">{{item.foo}}</div>
</div>

If you want to add a control to hide/show items with an exampleKey of false, you can change your loop to:

<div v-for="item in items">
  <div v-if="item.exampleKey || showItemsWithFalseExampleKey">{{item.foo}}</div>
</div>

And you can create a data property “showItemsWithFalseExampleKey” that is toggled by a button:

<button @click="showItemsWithFalseExampleKey = !showItemsWithFalseExampleKey">Toggle hidden items</button>

Of course, render cost for v-if is a lot higher than using v-show, so choose which is better based on your situation: https://v2.vuejs.org/v2/guide/conditional.html#v-if-vs-v-show

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement