Better reactivity in Vue.js 3
Vue 2 already had great reactivity, and you might not have come across any cases where you found that reactivity was lacking. However, there were a few cases where Vue 2 fell short.
Let’s revisit Vue 2 and see what those limitations were.
To demonstrate reactivity, we’ll use watchers to listen to one of the state variables and then modify it to see if the watchers
are triggered:
<template>
<div class="hello" @click="test">test {{list }} {{ myObj }}</div>
</template>
<script>
export default {
name: "HelloWorld",
data() {
return {
list: [1, 2],
myObj: { name: "Preetish" }
};
},
watch: {
list: {
handler: () => {
console.log("watcher triggered");
},
deep: true
}
},
methods: {
test() {
this.list[2] = 4;
this.myObj.last = "HS";
delete this.myObj.name;
}
}
};
</script>
None of the above three modifications — such as adding a new item to an array based on the index, adding a new item to an object, or deleting an item from the object — is reactive in Vue-2. Hence watchers
won’t be triggered, or the DOM would be updated. We had to use the vue.set()
or vue.delete()
methods.
In Vue-3, these work directly without any helper functions:
export default {
setup() {
let list = ref([1, 2])
let a = ref(0)
let myObj = ref({ name: 'Preetish' })
function myFun() {
list.value[3] = 3
myObj.value.last = 'HS'
delete myObj.value.name
}
return { myFun, list, myObj }
}
}
We can see that watcher
was triggered all four times in the Vue 3 setup.