1

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.

2
  • 1
    vuejs.org/v2/guide/list.html#Caveats Commented Jul 18, 2017 at 13:26
  • Thanks, that was really tricky seeing the object updated, but not the view... Commented Jul 18, 2017 at 13:36

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.