Detailed explanation and extension of ref and reactive in Vue3

Detailed explanation and extension of ref and reactive in Vue3

1. Ref and reactive

Remember: ref is also reactive in nature, ref(obj) is equivalent to reactive({value: obj})

  • The way to implement responsive data in Vue3 is to use ref and reactive. The so-called responsiveness means that the interface and data are synchronized and can be updated in real time.
  • In vue2, responsiveness is achieved through defineProperty, while in vue3, it is achieved through ES6 Proxy

1. reactive

  • The reactive parameter must be an object, including json data and arrays, otherwise it is not responsive.
  • If you pass other objects (such as a time object) to reactive, the modified object interface will not be automatically updated by default. If you want to update it, you can solve it by reassigning the object.

2.ref

Since we have reactive, why do we need ref? When we just want a variable to be responsive, it would be troublesome to use reactive. Therefore, vue3 provides the ref method for monitoring simple values. However, it does not mean that ref can only pass in simple values. Its underlying layer is reactive, so it has everything that reactive has. It’s the same old saying:

Remember: ref is also reactive in nature, ref(obj) is equivalent to reactive({value: obj})

  • Use the value of ref in vue without getting it through .value
  • To use the value of ref in js, you must get it through .value

2. shallowRef and shallowReactive

Recursive and non-recursive monitoring
Both ref and reactive belong to recursive monitoring, that is, each layer of data is responsive. If the amount of data is large, it will consume a lot of performance. Non-recursive monitoring will only monitor the first layer of data.

1. ref and shallowRef

  • Each layer of data defined by ref is responsive data
  • For data defined by shallowRef, only the first layer is responsive, that is, responsiveness can only be achieved when .value is changed
let age = ref({
      a: '1',
      f: {
        b: '2',
        s:{
          c: '3'
        }
      }
    })
//Print each layer's data console.log(age);
console.log(age.value);
console.log(age.value.f);
console.log(age.value.fs);

let age = shallowRef({
      a: '1',
      f: {
        b: '2',
        s:{
          c: '3'
        }
      }
    })
//Print each layer's data console.log(age);
console.log(age.value);
console.log(age.value.f);
console.log(age.value.fs);

After using shallowRef, you can actively update the interface through the triggerRef() method to achieve interface refresh

function doSome(){
  age.value.fsc = 'c';
  //Actively update the interface triggerRef(age);
}

2. reactive and shallowReactive

Note: shallowReactive does not have a method similar to triggerRef()

3. toRaw

What problem does toRaw solve?

Sometimes we don’t want the data to be updated in real time in a responsive manner. We can use toRaw to get the original data referenced by ref or reactive. Modifying the original data will not cause the interface to be updated. Responsive changes to the interface will only occur when modifying the data wrapped by ref and reactive.

let obj1 = {...};
//state and obj1 are referenced. The essence of state is a Proxy object, which references obj1
let state = reactive(obj1);
//Getting the original data through the toRaw method actually gets the memory address of obj1. obj2 and obj1 are completely equal. let obj2 = toRaw(state)
console.log(obj1 === obj2); //true

Some students may ask, isn't it enough to just use obj1 to modify the data? But the key is that when we use reactive to define data, we usually don't define an obj first and then pass it to reactive. We write data directly in reactive.

4. markRaw

Unlike toRaw, the data wrapped by markRaw will never be tracked!

I haven't found any use for it yet (manual dog head)

let obj1 = {name: "lijing", age: 18}
let obj2 = markRaw(obj1);
//At this time, although the data wrapped by reactive is a responsive object, it will not be tracked and will not produce any effect. let state1 = reactive(obj2)

console.log(obj1 === obj2); //true

5. toRef and toRefs

Both ref and toRef are used to construct responsive data. What is the difference between the two? Let's look at two examples.

1. ref

Copying and modifying responsive data will not affect previous data, and the interface will automatically update when the data changes

The converted type is a RefImpl

It can be seen that after using ref to responsively transform a simple data type attribute of an object, modifying the responsive data will not affect the original data. As shown in the figure above, after the value is modified by state1, the value of the a attribute in obj1 does not change. There is a point to note here: the modified attribute must be a simple data type, a specific value, and cannot be a reference. If the attribute is also an object, it will be affected because object-->reference!

For example, in the above example, if obj1.f is passed to state1, the situation will be completely different.

//Equivalent to let state1 = ref({b: '2',s: {c: '3'}})
// Also equivalent to --->let state1 = reactive({value: {....}}})
let state1 = ref(obj1.f);

2. toRef

If toRef is used for conversion, modifying the responsive data will affect the original data. The data will change, but the interface will not be automatically updated.

The converted type is an ObjectRefImpl

ref is similar to a deep copy, toref is similar to a shallow copy

3. toRefs

Iterates over all properties in an object and turns them into responsive data. This is because toRef can only pass one key. The effect achieved by toRefs is the same as toRef.

Tips: Currently, the most commonly used ones are ref and reactive, and other things are generally used to improve performance later.

Summarize

This is the end of this article about ref and reactive in Vue3. For more relevant Vue3 ref and reactive content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of the usage of setUp and reactive functions in vue3
  • The complete usage of setup, ref, and reactive in Vue3 combination API
  • Vue3's problem and solution on reactive reset

<<:  Detailed explanation of MySQL database--multi-table query--inner join, outer join, subquery, correlated subquery

>>:  How to install yum source and upload and download commands rz and sz under CentOS7 (with pictures)

Recommend

Detailed explanation of Nginx version smooth upgrade solution

Table of contents background: Nginx smooth upgrad...

Goodbye Docker: How to Transform to Containerd in 5 Minutes

Docker is a very popular container technology. Th...

Four data type judgment methods in JS

Table of contents 1. typeof 2. instanceof 3. Cons...

Vue implements small notepad function

This article example shares the specific code of ...

Tutorial on installing Elasticsearch 7.6.2 in Docker

Install Docker You have to install Docker, no fur...

How to safely shut down MySQL

When shutting down the MySQL server, various prob...

Vue.js uses Element-ui to implement the navigation menu

This article shares the specific code for impleme...

Superficial Web Design

<br />I have always believed that Yahoo'...

The difference between redundant and duplicate indexes in MySQL

MySQL allows you to create multiple indexes on a ...

15 JavaScript functions worth collecting

Table of contents 1. Reverse the numbers 2. Get t...

Detailed explanation of nginx reverse proxy webSocket configuration

Recently, I used the webSocket protocol when work...