Detailed analysis of the difference between Ref and Reactive in Vue3.0

Detailed analysis of the difference between Ref and Reactive in Vue3.0

Ref and Reactive

Ref

Ref is used to create basic types of responsive data. The template calls value to display data by default. Modifications in the method require the value of value to be modified

<!-- Template syntax> 
<template>
   <div>{{state}}</div>
</template> 
//js script setup(){
     let state = ref(10) 
     state.value = 11
     return {state}
}

Reactive

Reactive is used to create responsive data of reference type.

<!-- Template syntax> 
<template>
   <div>{{state.name}}</div>
</template> 
//js script setup(){
     let state = reactive({name:'aaa'}}) 
     state.name = 'zhangsan'
     return {state}
}

The difference between Ref and Reactive

The essence of Ref is created through Reactive, Ref(10)=>Reactive({value:10});

Ref can directly omit value in template calls. To change the value of the variable in the method, you need to modify the value of value in order to successfully change it. Reactive must be written in full in the template otherwise the entire data will be displayed.

The essence of Reactive is to parse the numbers of each layer into proxy objects. Reactive's responsiveness is recursive by default. Changing the value of a certain layer will recursively call it again and re-render the DOM.

shallowRef and shallowReactive

Ref and Reactive create recursive responses, parsing each layer of json data into a proxy object. shallowRef and shallowReactive create non-recursive response objects. The data created by shallowReactive will re-render the DOM if the first layer of data changes.

 var state = shallowReactive({
    a:'a',
    gf:{
       b:'b',
       f:{
          c:'c',
          s:{d:'d'}
       }
    }
 })
 state.a = '1'
 //Changing the first layer of data will cause the page to be re-rendered //state => Proxy {a:"a",gf:{...}}
//If you don't change the first layer and only change other data, the page will not be re-rendered, for example, state.gf.b = 2

The responsive object created by shallowRef needs to modify the entire value to re-render the DOM

var state = shallowRef({
   a:'a',
    gf:{
       b:'b',
       f:{
          c:'c',
          s:{d:'d'}
       }
    }
})
state.value.a = 1
/*
It cannot be re-rendered. The principle of shallowRef is also created through shallowReactive({value:{}}). You need to modify the value to re-render*/
state.value = {
    a:'1',
    gf:{
       b:'2',
       f:{
          c:'3',
          s:{d:'d'}
       }
    }
}

If you use shallowRef and want to update only a certain layer of data, you can use triggerRef

var state = shallowRef({
   a:'a',
    gf:{
       b:'b',
       f:{
          c:'c',
          s:{d:'d'}
       }
    }
})
state.value.gf.fsd = 4
triggerRef(state)

The page will re-render

toRaw --- Only modify the data without rendering the page

If you only want to modify responsive data without causing page rendering, you can use the toRaw method.

var obj = {name:'test'}
var state = reactive(obj)
var obj2 = toRaw(state)
obj2.name = 'zs' // does not cause the page to render----
//If it is created with ref, then get the value var obj = {name:'test'}
var state = ref(obj)
var obj2 = toRaw(state.value)

markRaw --- Do not track data

If you don't want the data to be tracked, you can call this method to make it responsive. Then you can't track the modified data and re-render the page.

var obj = {name:'test'}
obj = markRaw(obj)
var state = reactive(obj)
state.name = 'zs' // Data page cannot be modified and will not be modified

toRef --- Associate with the data source without modifying the UI

If you use ref to create a responsive variable, it will not be associated with the source data. If you want to associate it with the source data but not update the UI when the data changes, you need to use toRef to create it.

var obj = {name:'test'}
var state = ref(obj.name)
state.name = 'zs' //At this time, the name attribute value of obj will not change, and the UI will be automatically updated///
var obj = {name:'test'}
var state = toRef(obj,'name') //Only one attribute value can be set state.name = 'zs' //The name attribute value in obj will change, but the UI will not be updated

toRefs ---Set multiple toRef property values

If you want to set multiple toRef property values, you can use toRefs

var obj = {name:'test',age:16}
var state = toRefs(obj)
state.name.value = 'zs' //The property value of obj's name will also change, but the UI will not be updated state.age.value = 18 //The property value of obj's age will also change, but the UI will not be updated

customRef ---Customize a ref

You can customize a responsive ref method through the customRef method

function myRef(value){
   /*
    The customRef function returns an object with two methods, get/set. The get method can be accessed when the created object obtains data, and the set method will be triggered when the created object modifies the value. The customRef function has two parameters, track/trigger. The track parameter means tracking. It is called in the get method to track data changes at any time. The trigger parameter is used to trigger the response. The set method can be called to update the UI interface*/
    return customRef((track,trigger)=>{
       return {
          get(){
             track()//tracking data return value     
          },
          set(newVal){
             value = newVal
             trigger()//Update UI interface}
       }
    })

}

setup(){
   var age = myRef(18)
   age.value = 20
}

ref The label of the bundled page

Vue2.0 can get DOM elements through this.refs, but Vue3 cancels this operation. Without refs, you can directly use the ref() method to generate responsive variables and bind them to DOM elements.

<template>
   <div ref="box"></div>

</template>
import {ref,onMounted} from 'vue'
/*
 The setup method is called between beforeCreate and created in the life cycle*/
<script>
   setup(){
      var box = ref(null)
      onMounted(()=>{
         console.log('onMounted',box.value)
      })
      console.log(box.value)
      return {box}

   }

</script>

Summarize

This is the end of this article about the difference between Ref and Reactive in Vue3.0. For more information about the difference between Ref and Reactive in Vue3.0, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Reactive function declaration array method in Vue3
  • In-depth understanding of reactive in Vue3
  • Do you know ref, computed, reactive and toRefs of Vue3?
  • setup+ref+reactive implements vue3 responsiveness
  • Introduction to reactive function toRef function ref function in Vue3
  • Solution to reactive not being able to assign values ​​directly in Vue3

<<:  Detailed discussion of MySQL stored procedures and stored functions

>>:  Detailed tutorial on installing phpMyAdmin on Ubuntu 18.04

Recommend

Play mp3 or flash player code on the web page

Copy code The code is as follows: <object id=&...

Introduction to setting up Tomcat to start automatically on Linux system

1. Enter the /etc/init.d directory: cd /etc/init....

Understanding MySQL Locking Based on Update SQL Statements

Preface MySQL database lock is an important means...

Detailed explanation of how to restore database data through MySQL binary log

Website administrators often accidentally delete ...

Summary of MySQL time statistics methods

When doing database statistics, you often need to...

Nginx cache files and dynamic files automatic balancing configuration script

nginx Nginx (engine x) is a high-performance HTTP...

MySQL 5.7.21 installation and configuration method graphic tutorial (window)

Install mysql5.7.21 in the window environment. Th...

mysql creates root users and ordinary users and modify and delete functions

Method 1: Use the SET PASSWORD command mysql -u r...

Detailed explanation of 8 ways to pass parameters in Vue routing components

When we develop a single-page application, someti...

How to configure Hexo and GitHub to bind a custom domain name under Windows 10

Hexo binds a custom domain name to GitHub under W...

Use CSS content attr to achieve mouse hover prompt (tooltip) effect

Why do we achieve this effect? ​​In fact, this ef...