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

MySQL data type optimization principles

MySQL supports many data types, and choosing the ...

In-depth understanding of the use of the infer keyword in typescript

Table of contents infer Case: Deepen your underst...

Understanding the CSS transform-origin property

Preface I recently made a fireworks animation, wh...

jQuery plugin to implement minesweeper game (1)

This article shares the specific code of the firs...

js memory leak scenarios, how to monitor and analyze them in detail

Table of contents Preface What situations can cau...

JavaScript data structure bidirectional linked list

A singly linked list can only be traversed from t...

Analysis of MySQL cumulative aggregation principle and usage examples

This article uses examples to illustrate the prin...

js realizes packaging multiple pictures into zip

Table of contents 1. Import files 2. HTML page 3....

How to encapsulate axios request with vue

In fact, it is very simple to encapsulate axios i...

Sample code for implementing honeycomb/hexagonal atlas with CSS

I don’t know why, but UI likes to design honeycom...

WeChat applet custom bottom navigation bar component

This article example shares the specific implemen...

MYSQL custom function to determine whether it is a positive integer example code

You can write a function: Mainly use regular expr...

Solution to MySQL service 1067 error: modify the mysql executable file path

Today I encountered the MySQL service 1067 error ...