This article will take you throughVue.js3 ref and reactive, and introduce the difference between ref and reactive. I hope it will be helpful to everyone!
Key points
reactive()
Only accepts objects As parameters, JS primitive types (String, Boolean, Number, BigInt, Symbol, null, undefined) are not supported. [Related recommendations:vue.js tutorial]
ref()
will callreactive()
in the background becausereactive()
supports objects, andref()
internally callsreactive()
, so both methods support objects
However,ref()
There is a.value
attribute that can be used to reassign a value, butreactive()
cannot be reassigned (responsiveness will be lost)
Usage scenarios
ref()
Used when the numerical type is a JS primitive type (For example,'string'
,true
,23
)
When an object is assigned and subsequently needs to be reassigned (for example, an array -See here for more)
reactive()
When the numerical type is an object and does not need to be reassigned When used,ref()
also callsreactive()
internally, without adding overhead
Summary
ref()
seems to be the right choice since it supports all object types and can be reassigned via.value
.ref()
is fine, but once you are familiar with the API, you will know thatreactive()
has less overhead, and you may find this more suitable for your needs.
ref() case
is initialized by usingref()
, butref()
Friendly to objects that need to be reassigned, such as arrays.
setup() { const blogPosts = ref([]); return { blogPosts }; } getBlogPosts() { this.blogPosts.value = await fetchBlogPosts(); }
If reactive() is used above, attribute assignment is required instead of object assignment.
setup() { const blog = reactive({ posts: [] }); return { blog }; } getBlogPosts() { this.blog.posts = await fetchBlogPosts(); }
reactive() case
##reactive()Suitable for initializing a group of data belonging to the same group:
const person = reactive({ name: 'Albert', age: 30, isNinja: true, });
const name = ref('Albert'); const age = ref(30); const isNinja = ref(true);
Programming Video! !
The above is the detailed content of Ref VS reactive in Vue3, what are the differences between them?. For more information, please follow other related articles on the PHP Chinese website!