Reputation: 1399
I need to update some Array data in my VueJS component which is rendering as a list in the template via v-for
.
When I update the whole Array, I see that the list updates in the DOM. But, if I update only an index, the list does not update.
Here are the two relevant methods:
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'
}];
}
}
Upvotes: 1
Views: 803
Reputation: 55674
From the documentation:
Due to limitations in JavaScript, Vue cannot detect the following changes to an array:
When you directly set an item with the index, e.g.
vm.items[indexOfItem] = newValue
When you modify the length of the array, e.g.
vm.items.length = newLength
To get Vue to react to the change of an array's index, use the Vue.set()
method.
In your case, you should use Vue.set(this.data, 0, newValue)
in your loadOnlyOneIndex
method.
Every Vue instance also has an alias to the Vue.set
method via vm.$set
(where vm
is the Vue instance).
So, you could also use this.$set(this.data, 0, newValue)
in your loadOnlyOneIndex
method.
This is helpful when using Single File Components, or anywhere where you don't have a direct reference to the Vue
object.
Upvotes: 1