VueJS数组项上的虚拟字段



我正在用VueJS构建一些东西,我在列表中选择一个项目时遇到了一些问题:

让我们想象下面的VueJS组件:

new Vue({
    el: '#app',
  data: {
    list: [
        {
        id: 1,
        title: 'My first Item',
        selected: false
      },
      {
        id: 2,
        title: 'My second Item',
        selected: false
      }
    ]
  }
})

使用selected属性,我可以对项目应用类或不应用类:

<div id="app">
  <ul>
    <li @click="item.selected = !item.selected" :class="item.selected ? 'active' : ''" v-for="item in list">{{ item.title }}</li>
  </ul>
</div>

但是现在,让我们假设我从API获取数据,我仍然希望能够选择项目:

new Vue({
    el: '#app',
  data: {
    list: []
  },
  created: function () {
    // Let's imagine that this is an Ajax Call to a webservice
    this.$set('list', [
      {
        id: 1,
        title: 'My first Item'
      },
      {
        id: 2,
        title: 'My second Item'
      }
    ])
  }
})

现在,我的html不能再工作了,因为数据没有选择的属性。

那么我怎么能做这样的事情呢?

下面是解释这个问题的两个JsFiddle:

  • 正在工作的
  • 不工作的

请阅读vue生命周期文档:

我希望您将列表设置为一个计算属性,它总是检查返回的项:即

new Vue({
    el: '#app',
  data: {
    list: []
  },
  computed: {
   list (){
    // Let's imagine that this is an Ajax Call to a webservice
    let returned =  [
      {
        id: 1,
        title: 'My first Item'
      },
      {
        id: 2,
        title: 'My second Item'
      }
    ]
     return returned
   }
  }
})

最新更新