Home> Web Front-end> Vue.js> body text

Ref VS reactive in Vue3, what are the differences between them?

青灯夜游
Release: 2021-10-25 10:09:10
forward
5255 people have browsed it

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!

Ref VS reactive in Vue3, what are the differences between them?

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.valueattribute 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(); }
Copy after login

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(); }
Copy after login

reactive() case

##reactive()Suitable for initializing a group of data belonging to the same group:

const person = reactive({ name: 'Albert', age: 30, isNinja: true, });
Copy after login

The above code is more logical than the one below

const name = ref('Albert'); const age = ref(30); const isNinja = ref(true);
Copy after login
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!

Related labels:
source:learnku.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn