Karlom
Karlom

Reputation: 14834

How to show/hide v-for elements in a dynamic array?

I'd like to show/hide each todo detail in a boxe,when corresponding todo button is clicked. In reality both todos and todoDetails are obtained dynamically from server.

The script is like this

var demo = new Vue({
  el: '#demo',
  data: {
    title: 'todos',
    seen: false,
    todos: ['eat', 'work'] ,//dynamic array  
    todoDetails: [{'eat': 'some yummy food'}, {'work': 'as hard as you can'}]
  },
  methods: {
    openbox: function() {
      seen = !seen ;
    }
  }
});

And the template is like:

<div id="demo" v-cloak>
  <h1>{{title }}</h1>

  <ul>
    <li v-for="todo in todos" @click="openBox">
      <button @click="openbox">{{ todo }}</button>
      <p v-show="seen"> More info: {{todoDetails[todo]}} </p>
    </li>
  </ul>
</div>

But I can not get it to work. How can I fix it?

Upvotes: 1

Views: 1161

Answers (1)

Matej Marconak
Matej Marconak

Reputation: 1413

I update your jsfiddle.

Base problem was:

  • @click="openBox" but name of function is @click="openbox"
  • seen = !seen ; add this keyword this.seen = !this.seen;

Template:

<div id="demo" v-cloak>
  <h1>{{title }}</h1>
  <ul>
    <li v-for="todo in todos" @click="openbox(todo)">
      <button>{{ todo.name }}</button>
      <p v-show="todo.seen"> To do details for {{todoDetails[todo.name]}} </p>
    </li>
  </ul>
</div>

Vue

var demo = new Vue({
  el: '#demo',
  data: {
    title: 'todos',
    seen: false,
    todos: [{
      name: 'eat',
      seen: false
    }, {
      name: 'work',
      seen: false
    }], //dynamic array  
    todoDetails: {
      'eat': 'some yummy food',
      'work': 'as hard as you can'
    }
  },
  methods: {
    openbox: function(todo) {
      todo.seen = !todo.seen;
    }
  }
})

Upvotes: 1

Related Questions