Middle
How does reactivity work in Vue 3? What is the difference from Vue 2 (Proxy vs Object.defineProperty)?
sobes.tech AI
Answer from AI
In Vue 3, reactivity is implemented using Proxy, unlike Vue 2, which used Object.defineProperty.
Differences:
- Proxy allows intercepting operations on the entire object, including adding and removing properties, which is not possible with Object.defineProperty.
- Thanks to Proxy, reactivity has become more complete and performant.
- Vue 3 can track changes in arrays and objects without needing to traverse all properties during initialization.
Example of using Proxy for reactivity:
const state = new Proxy({ count: 0 }, {
get(target, prop) {
console.log(`Reading property ${prop}`);
return target[prop];
},
set(target, prop, value) {
console.log(`Setting ${prop} = ${value}`);
target[prop] = value;
// here you can notify subscribers
return true;
}
});
state.count = 1; // Set count = 1
console.log(state.count); // Read property count
In Vue 2, reactivity was created using Object.defineProperty for each property, which limited dynamic addition of new properties and complicated change tracking.