Home >Web Front-end >Vue.js >Ref VS reactive in Vue3, what are the differences between them?
This article will take you through Vue.js 3 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 call reactive()
in the background because reactive()
supports objects, and ref()
internally calls reactive()
, so both methods support objects
However, ref()
There is a .value
attribute that can be used to reassign a value, but reactive()
cannot be reassigned (responsiveness will be lost)
Usage scenarios
<strong>ref()</strong>
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)
<strong>reactive()</strong>
When the numerical type is an object and does not need to be reassigned When used, ref()
also calls reactive()
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 that reactive()
has less overhead, and you may find this more suitable for your needs.
ref() case
is initialized by using ref()
, but ref()
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, });The above code is more logical than the one below
const name = ref('Albert'); const age = ref(30); const isNinja = ref(true);For more programming-related knowledge, please visit:
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!