I'm a bit new to JS and Vue and am not quite sure if I understood the documentation correctly. It says:
Due to the limitations of modern JavaScript (and the abandonment of
Object.observe
), Vue cannot detect property addition or deletion. Since Vue performs the getter/setter conversion process during instance initialization, a property must be present in the data object in order for Vue to convert it and make it reactive.
Does this include normal arrays as well, or do elements in arrays not count as "properties" in JavaScript?
I wish to do state.array.push(data)
to an array. Is this the correct way to do it?
This is covered in good detail in the Change Detection Caveats section of the docs. For Arrays specifically:
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
The specifics of Array prototype methods are also covered under the list rendering section:
Vue wraps an observed array’s mutation methods so they will also trigger view updates. The wrapped methods are:
push()
pop()
shift()
unshift()
splice()
sort()
reverse()
So the answer to the question is state.array.push
reactive? is yes.
Note, however, that the above caveats only apply to Vue 2.
Vue 3 brought a complete overhaul to the reactivity mechanism, switching from using object getters and setters to using an ES6 JavaScript feature called Proxy
.
This allows more comprehensive object change monitoring with less setup and less caveats for the user to worry about.