2017-07-18 127 views
1

组件的数组索引的数据我需要更新我的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' 
    }]; 
    } 
} 

Here is a fiddle.

+1

https://vuejs.org/v2/guide/list.html#Caveats – thanksd

+0

谢谢,这是真正棘手看到对象更新,但不认为... – moabi

回答

0

documentation

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

  1. 当您直接设置的项目与指标,例如vm.items[indexOfItem] = newValue

  2. 当修改所述阵列的长度,例如vm.items.length = newLength

要获得Vue的反应到一个数组的索引的变化,使用Vue.set() method


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

Here's a working fiddle.


每Vue的实例也具有经由vm.$set的别名Vue.set方法(其中vm是Vue的实例)。

所以,你也可以在你的loadOnlyOneIndex方法使用this.$set(this.data, 0, newValue)

当使用Single File Components时,或者您没有直接参考Vue对象时,这会很有帮助。