In this example, we simply have an array of numbers from one to five, which is output in an unordered list using the v-for directive. There is also a button which invokes a click event handler that changes the number stored at the second position to ten. What do you think would happen if I run this code and click the button? Let’s try.
As expected we see an alert dialog with the new number, indicating that the array element has indeed been updated to ten.
I will replace the statement that clearly didn’t work with a new statement which invokes Vue.set. This method takes three arguments; the first is a reference to the object or array on which we want to change a value – this.numbers in this case. We need to prefix with the this keyword because we are inside a method on our Vue instance. The second argument is the key that we would like to change. Because we wish to change an element within an array in this case, this will correspond to the array index. The last argument is the value that we want to set on the first argument, in this case the number ten.
Vue.set(this.numbers, 1, 10);
Note that the reference that you pass as the first argument cannot be either a Vue instance or the root data object of a Vue instance.
Running the code again, we will see that the list is now updated as we would have expected in the first place. So in cases where Vue.js cannot detect changes made to your data, you can use the Vue.set method, and Vue.js will happily trigger an update to your view.
In this post we saw a limitation of Vue.js’ change detection, but saw how to deal with it by using the Vue.set method.
Learn Vue.js today!
Take an online course and become an Vue.js champion!
Here is what you will learn:
- How to build advanced Vue.js applications (including SPA)
- How Vue.js works under the hood
- Communicating with services through HTTP
- Managing state of large applications with Vuex
- ... and much more!
One comment on »Array Change Detection in Vue.js«
Thanks for the great tutorial. I have created a jsfiddle that updates the array here https://jsfiddle.net/MarvGeek/68f6ckj6/29/ without using Vue.set which works fine, but on the real app a environment is not updating, can you perhaps tell me why??