The difference between ref and reactive in vue3?

The difference between ref and reactive in vue3


the difference

  1. The difference between ref and reactive:
    If the data of ref type is used in the template, then Vue will automatically add .value for us;
    if the data of reactive type is used in the template, then Vue will not automatically add .value for us
  2. How does Vue decide whether to automatically add .value?
    Before parsing the data, Vue will automatically judge whether the data is of ref type.
    If it is, it will automatically add .value, if not, it will not automatically add .value
  3. How does Vue judge whether the current data is of ref type?
    Judging by the __v_ref of the current data
    . If there is this private attribute and the value is true, it means it is a ref type of data

data is of type ref

<template>
  <div>
    <p>{
    
    {
    
     age }}</p>
    <button @click="Fn">按钮</button>
  </div>
</template>
 
<script>
import {
    
     ref } from "vue";
export default {
    
    
  name: "App",
  setup() {
    
    
    // ref类型在底层会自动转换成reactive类型
    // ref(18) -> reactive({value: 18})
    let age = ref(18);
 
    function Fn() {
    
    
      age.value = 666;
    console.log(age)
    }
    return {
    
     age, Fn };
  },
};
</script>

The data is of reactive type

<template>
  <div>
    <p>{
    
    {
    
    age}}</p>
    <button @click="Fn">按钮</button>
  </div>
</template>
 
<script>
 
import {
    
    reactive} from 'vue';
 
export default {
    
    
  name: 'App',
  setup() {
    
    
    let age = reactive({
    
    value: 18});
    function Fn() {
    
    
        age.value = 666;
   	console.log(age)
    }
    return {
    
    age, Fn}
  }
}
</script>

How do we judge whether the data is ref or reactive?

via the isRef / isReactive method

<template>
  <div>
    <p>{
    
    {
    
    age}}</p>
    <button @click="Fn">按钮</button>
  </div>
</template>
 
<script>
import {
    
    reactive} from 'vue';
export default {
    
    
  name: 'App',
  setup() {
    
    
    let age = reactive({
    
    value: 18});
    function Fn() {
    
    
       console.log(isRef(age)); //false
       console.log(isReactive(age));  //true
       age.value = 666;
    }
    return {
    
    age, Fn}
  }
}
</script>

Guess you like

Origin blog.csdn.net/zhaojiaxing123/article/details/129539064