Reactivity Caveats
Learn how the reactivity system has changed in Vue 3.
One significant change coming with Vue 3 is the reactivity system implementation.
Vue 2
In Vue 2, to make data reactive, getters and setters of Object.defineProperty
were used. However, this came with a few reactivity caveats.
For instance, to ensure the reactivity of a property on a data object, it must be added to the state during initialization. Vue 2 can’t detect property addition or deletion, as shown in the example below:
Press + to interact
const vm = new Vue({data() {return {count: 1,user: {}}}})// vm.count is reactivevm.user.name = 'Max'// vm.user.name is not reactive
However, new properties can be added using the Vue.set
method or the this.$set
method available on Vue’s component instance.
Press + to interact
Vue.set(vm.user, 'name', 'Daisy')// or inside of a componentthis.$set(this.user, 'name', 'Lincoln')
Moreover, Vue 2 is unable to detect the following array changes:
- When setting an item using an index, like,
vm.items[itemIndex] = newValue
- When modifying array length, like
vm.items.length = newLength
The first can be addressed by using the Vue.set
or splice
...