I have a simple page made in vue, where in the data there is an object of the following form:
data: function () {
return {
titulo: '',
elementos: Object
}
}
Now, elements is defined as an object, however, when I make a change to one of its properties:
elementos.propiedad1 = 4;
Nothing happens, my eyesight doesn't react to changes.
I do not understand why this happens, nor why it is not reactive, if the element is defined in the data. That could be happening?
TL;DR;
Objects are not reactive in vue per se, you need to tell vue that an object has changed to be reactive. You have to set the object using set or Object.assign
Change detection issues
Object properties do not behave as expected. Changes to them don't cause vue to react to changes as you'd expect.
When one changes an object:
One would expect that if that is shown in the view
the same change. But this does not happen.
This is because the properties of the object itself are not reactive, because when initializing it, vue created a wacth to detect changes in the object, not in its properties.
Therefore, changing properties does not have the expected effect, unless the methods recommended by vue are used so that they are detected.
These methods can be used both to change the values of the object, as well as to add new properties.
The object can be made to react, by making a new object and assigning it to the old one:
You can use the Vue.Set method to add properties to it
You can also use this.$set which is a global alias for the above method.
If you want to modify one or more properties, you can use this method to take care of comparing the objects and returning a new one with the changed properties.
Using one of the methods described above, cause the object to be picked up by vue's watchers, and react accordingly in all cases.