1

I try to give v-if="seen" for some class but it doesn't work obviously...

My code:

<div class="item" v-if="seen">item 1</div>
<div class="item" v-if="seen">item 2</div>
<div class="item" v-if="seen">item 3</div>

var item = new Vue({
   el: 'div.item',
   data: {
       seen: true
   }
});

In JavaScript I could do :

var item = document.getElementsByClassName('item');
for(var i = 0; i < item.length; i++){
    item[i].style.display = "none";
}

How must I do in Vue.js ? Thanks

1
  • Your use of v-if is correct. You don't want to be setting up separate Vue instances for each div.item, though; that should be a single element containing the other divs. Commented Aug 9, 2018 at 13:50

4 Answers 4

2

You can try using a v-for and setup the data to use an array.

Try something like this:

<div id="app">
    <div v-for="myItem in items" class="item" v-if="myItem.seen">{{myItem.name}}</div>
</div>

var app = new Vue({
   el: '#app',
   data: {
       items : [{
           seen: true,
           name: 'item 1'
       },
       {
           seen: false,
           name: 'item 2'
       },
       {
           seen: false,
           name: 'item 3'
       }]
   }
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks you so much
No problem :) Have fun coding
2

The way Vue is designed, it should be ideally done like so:

<div id="app">
    <div class="item" v-if="seen">item 1</div>
    <div class="item" v-if="seen">item 2</div>
    <div class="item" v-if="seen">item 3</div>
</div>

var app = new Vue({
   el: '#app',
   data: {
       seen: true
   }
});

3 Comments

The problem is how I do for apply seen:true for only one item and false for others then ?
check my answer... it should do exactly what you need.
You would need different variables controlling each of them, then.
0

There is many ways to achieve what you want. Example of one of them:

<div is="app">
  <div class="item" v-if="!seen.includes('item1')">
    item 1
  </div>
  <div class="item" v-if="!seen.includes('item2')">
    item 2
  </div>
  <div class="item" v-if="!seen.includes('item3')">
    item 3
  </div>
</div>

var item = new Vue({
  el: '#app',
  data: {
    seen: [
      'item1',
      'item3'
    ]
  }
})

Comments

-1

var item = new Vue({
   el: 'div.item',
   data: {
       isSeen: true
   },
    computed:{
     seen:()=>this.isSeen;
    }
});

or you could use v-show or v-class

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.