Vuejs2 组件';s数组索引数据未更新

Vuejs2 组件';s数组索引数据未更新,vuejs2,vue-component,Vuejs2,Vue Component,我需要更新VueJS组件中的一些数组数据,该组件将通过v-for在模板中呈现为列表 当我更新整个数组时,我看到列表在DOM中更新。但是,如果只更新索引,则列表不会更新 以下是两种相关的方法: methods: { loadOnlyOneIndex: function() { this.data[0] = { title: 'Hello error', slug: 'hello', desc: 'will not work' }; },

我需要更新VueJS组件中的一些数组数据,该组件将通过
v-for
在模板中呈现为列表

当我更新整个数组时,我看到列表在DOM中更新。但是,如果只更新索引,则列表不会更新

以下是两种相关的方法:

methods: {
  loadOnlyOneIndex: function() {
    this.data[0] = {
      title: 'Hello error',
      slug: 'hello',
      desc: 'will not work'
    };
  },
  loadEverything: function() {
    this.data = [{
      title: 'Hello new title',
      slug: 'hello',
      desc: 'this will work'
    }, {
      title: 'Hello new title 2 !',
      slug: 'hello2',
      desc: 'really work'
    }];
  }
}

来自:

由于JavaScript的限制,Vue无法检测到对数组的以下更改:

  • 直接使用索引设置项目时,例如
    vm.items[indexOfItem]=newValue

  • 修改数组长度时,例如
    vm.items.length=newLength

  • 要使Vue对数组索引的更改作出反应,请使用


    在您的情况下,应该在
    loadOnlyOneIndex
    方法中使用
    Vue.set(this.data,0,newValue)


    通过
    vm.$set
    (其中
    vm
    是Vue实例),每个Vue实例还具有
    Vue.set
    方法的别名

    因此,您也可以在
    loadOnlyOneIndex
    方法中使用
    this.$set(this.data,0,newValue)


    这在使用时很有用,或者在没有直接引用到
    Vue
    对象的任何地方也很有用。

    谢谢,看到对象更新了,但视图没有更新,这真的很棘手。。。