moabi
moabi

Reputation: 1399

Component's Array index data not updating

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'
    }];
  }
}

Here is a fiddle.

Upvotes: 1

Views: 803

Answers (1)

thanksd
thanksd

Reputation: 55674

From the documentation:

Due to limitations in JavaScript, Vue cannot detect the following changes to an array:

  1. When you directly set an item with the index, e.g. vm.items[indexOfItem] = newValue

  2. 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.

Here's a working fiddle.


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

Related Questions