Vuejs2 组件';s数组索引数据未更新
我需要更新VueJS组件中的一些数组数据,该组件将通过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' }; },
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
在您的情况下,应该在
loadOnlyOneIndex
方法中使用Vue.set(this.data,0,newValue)
通过
vm.$set
(其中vm
是Vue实例),每个Vue实例还具有Vue.set
方法的别名
因此,您也可以在loadOnlyOneIndex
方法中使用this.$set(this.data,0,newValue)
这在使用时很有用,或者在没有直接引用到
Vue
对象的任何地方也很有用。谢谢,看到对象更新了,但视图没有更新,这真的很棘手。。。