如何在动态数组中显示/隐藏v-for元素?

时间:2017-03-19 05:37:44

标签: javascript vue.js

我希望在点击相应的todo按钮时显示/隐藏boxe中的每个待办事项详细信息。 实际上,todostodoDetails都是从服务器动态获取的。

该脚本类似于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 ;
    }
  }
});

模板就像:

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

但我无法让它发挥作用。我该如何解决?

1 个答案:

答案 0 :(得分:1)

我更新了您的jsfiddle

基本问题是:

  • @click="openBox"但功能名称为@click="openbox"
  • seen = !seen ;添加this关键字this.seen = !this.seen;

模板:

<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;
    }
  }
})