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

Basic operations of mysql learning notes table

Create Table create table table name create table...

MySQL uses UNIQUE to implement non-duplicate data insertion

SQL UNIQUE constraint The UNIQUE constraint uniqu...

Native JS to achieve book flipping effects

This article shares with you a book flipping effe...

Book page turning effects made with CSS3

Result:Implementation code: html <!-- Please h...

JS realizes the effect of picture waterfall flow

This article shares the specific code of JS to re...

Reasons and solutions for the failure of React event throttling effect

Table of contents The problem here is: Solution 1...

Vue uses element-ui to implement menu navigation

This article shares the specific code of Vue usin...

HTML head tag detailed introduction

There are many tags and elements in the HTML head ...

We're driving IE6 to extinction on our own

In fact, we wonder every day when IE6 will really...

JavaScript to implement search data display

This article shares the data display code for Jav...