In Vue 3, the Vue.set method from the Vue 2.x version is no longer needed because Vue 3 uses a Proxy-based reactivity system that natively supports reactive handling of adding or deleting properties on objects.
In Vue 2.x, if you want to add a new property to a reactive object while maintaining reactivity, you need to use the Vue.set function or the instance method $set. However, in Vue 3, by directly using standard JavaScript to add properties, Vue's reactivity system automatically detects these changes.
Example
Suppose you have a Vue 3 component whose data function returns an object that initially lacks certain properties:
javascriptexport default { data() { return { userProfile: { name: 'Zhang San' } }; } }
If you want to add a new property age to the userProfile object within a method while maintaining reactivity, you can do it directly:
javascriptmethods: { addAge() { this.userProfile.age = 30; } }
When you do this, the userProfile object will automatically update, and the interface will update accordingly to display the newly added age property.
Note
Although Vue 3's reactivity system natively supports this operation, there are some considerations to keep in mind:
- It's best to define all properties at the time of object creation to improve performance and code readability.
- If you have a very large object or array and only update a small part of it, using Vue 3's
reactiveorrefto wrap these objects and modifying them as needed might be more efficient.
In summary, Vue 3's reactivity system provides developers with greater flexibility and powerful features, making development more convenient and efficient.