Get the App
SLTechnology News&Howtos  ›  Development  › 

What is the difference between ref and reactive in Vue3

Shulou Source: shulou.com Published: 2022-06-03 00:53:16 10月03日 Update

This article introduces the relevant knowledge of "what is the difference between ref and reactive in Vue3". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Key points

Reactive () only accepts objects as parameters and does not support JS primitive types (String, Boolean,Number,BigInt,Symbol,null,undefined). [related recommendation: vue.js tutorial]

Ref () calls reactive () in the background.

Both methods support objects because reactive () supports objects, while ref () calls reactive () internally.

However, ref () has a .value attribute that can be reassigned, while reactive () cannot be reassigned (it loses responsiveness)

Working with scen

Ref ()

Used when the numeric type is a JS primitive type (for example, 'string', true, 23)

When an assigned object needs to be reassigned later (for example, an array-see here for more)

Reactive ()

When the numeric type is an object and does not need to be reassigned, reactive () is also called inside ref (), so there is no need for additional overhead.

Summary

Ref () seems to be the right choice because it supports all object types and can be reassigned via .value. Ref () is fine, but when you are familiar with API, you know that reactive () is less expensive and may find this more satisfying.

Ref () case

Initialized by using ref (), but ref () is friendly to objects that need to be reassigned, such as arrays.

Setup () {const blogPosts = ref ([]); return {blogPosts};} getBlogPosts () {this.blogPosts.value = await fetchBlogPosts ();}

If you use reactive () above, you need attribute assignment instead of object assignment.

Setup () {const blog = reactive ({posts: []}); return {blog};} getBlogPosts () {this.blog.posts = await fetchBlogPosts ();}

Reactive () case

Reactive () is suitable for initializing a set of data with the same attribution:

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); so much for the introduction of "what's the difference between ref and reactive in Vue3". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Tags: Object type support more case primitive content attribute overhead numeric array knowledge faceted practical identical learned next two code key Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Linux Shulou Technology Redmi NVidia Shulou Information