乐闻世界logo
搜索文章和话题

How do I do Vue.set() in Vue 3?

1个答案

1

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:

javascript
export 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:

javascript
methods: { 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 reactive or ref to 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.

2024年10月27日 17:37 回复

你的答案