Inchara Raveendra
Inchara Raveendra

Reputation: 1667

Hide and show elements with v-if

Here is my fiddle : DEMO

new Vue({
  el: '#app',
  data: {
    modules: ['abc', 'def']
  }
})

How can I hide/show with v-if based on the values found in an array ( modules[] ) ?

Any help would be appreciated. Thank you.

Upvotes: 0

Views: 1659

Answers (1)

Kirk Larkin
Kirk Larkin

Reputation: 93003

You have at least a couple of options to manage this, which I'll describe here. The first is a simple check inside of v-if to see if the item is contained within modules. For example:

<div class="abc box" v-if="modules.indexOf('abc') >= 0">abc</div>
<div class="def box" v-if="modules.indexOf('def') >= 0">def</div>
...

This is a little bit crude and not great from a maintenance or performance perspective. Another option would be to use the modules array as the source for your collection of divs, using v-for. For example:

<div class="box" v-for="module in modules" :class="module">{{ module }}</div>

There's a few things to note here:

  1. v-for looks directly at the modules array to determine the number of divs to render.
  2. The value in the array is used both as the text for the div ({{ module }}) and as one of the classes (:class="module").
  3. The class box is always applied, using the standard class attribute. The combination of this and the :class binding end up with e.g. abc box as the class list.

Here's a working example demonstrating the v-for approach.

new Vue({
  el: '#app',
  data: {
    modules: ['abc', 'def']
  }
});
.box {
  height: 75px;
  width: 75px;
  background: #444;
  padding: 10px;
  margin: 5px;
  color: #fff;
}
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>

<div id="app">
  <div class="box" v-for="module in modules" :class="module">{{ module }}</div>
</div>

Upvotes: 1

Related Questions