Home >Web Front-end >Vue.js >How to solve the problems about ref and reactive in Vue3

How to solve the problems about ref and reactive in Vue3

WBOY
WBOYforward
2023-05-22 19:26:20891browse

    Questions about ref and reactive

    If you have used Vue3, you know that there are two very commonly used reactive APIs in Vue3: reactive and ref. They make the data we want to track responsive.

    We have always been told that ref can be used to create reactivity of basic types and reference types. For reference types, the bottom layer is also converted to reactive for responsive processing. That being the case, why do you need to use reactive? Wouldn’t it be enough to just use ref for everything?

    Although the reactive data created by ref requires .value to be accessed in the script, in this case, this will not have much impact on the program. The template automatically adds .value, so there is no need to use .value access in the template.

    Since there is basically no difference between the two, but the reactive API is still exposed, are there any scenarios that reactive can do but ref cannot?

    A brief understanding of ref & reactive

    Let’s first briefly understand these two APIs.

    reactive

    Returns a reactive copy of the object. Reactive transformations are "deep" - it affects all nested properties. We usually write like this.

    const obj = reactive({ count: 0 })

    and can be used directly.

    const count = obj.count

    ref

    Accepts an internal value and returns a responsive and mutable ref object. The ref object has only one .value property, which points to the inner value.. We usually write like this.

    const data = ref(xxx)

    When quoting, it is usually quoted through data.value.

    const dataValue = data.value

    By tracing the source code of Vue3, we can prove that when we call the ref method to define reactive data, when the parameter is an object type, the reactive method is actually used. That is, the property above data.value is created through the reactive method.

    Note:

    What reactive can do, ref can also do, and it is still done with reactive

    When the parameter of ref is an object, use The most important thing is the reactive method

    In Vue3, if you want to make object type data responsive, both reactive and ref can be used, and ref is supported internally through reactive. In other words, what you can do with reactive, I can do with ref.

    Simply speaking, ref is encapsulated and enhanced on reactive, so in Vue3, ref can also do what reactive can do, and ref can also do what reactive cannot do.

    Personally, I understand that ref is syntactic sugar for reactive. For example: ref(1) is equivalent to reactive({value: 1});

    Usually, it is okay to use ref for projects , the problem is not big

    The difference between vue3 ref and reactive

    Ref

    ref data responsive monitoring. The ref function passes in a value as a parameter, usually a basic data type, and returns a responsive Ref object based on the value. Once the value in the object is changed and accessed, it will be tracked, just like our rewritten example The code is the same. By modifying the value of count.value, you can trigger the re-rendering of the template and display the latest value

    <template>
      
      <h2>{{name}}</h2>
      <h2>{{age}}</h2>
      <button @click="sayName">按钮</button>
    </template>
    
    <script lang="ts">
    import {ref,computed} from &#39;vue&#39; 
    
    export default {
      name: &#39;App&#39;,
      setup(){
        const name = ref(&#39;zhangsan&#39;)
        const birthYear = ref(2000)
        const now = ref(2020)
        const age = computed(()=>{
          return now.value - birthYear.value
        })
        const sayName = () =>{
          name.value = &#39;I am &#39; + name.value
        }
        return {
          name,
          sayName,
          age
        }
      }
    }
    </script>

    reactive

    reactive is used to define more complex Data type, but after being defined, the variables inside are no longer responsive Ref object data

    So you need to use the toRefs function to convert it into a responsive data object

    How to solve the problems about ref and reactive in Vue3

    Convert the code written above using ref into reactive code

    <template>
      <!-- <img alt="Vue logo" src="./assets/logo.png"> -->
      <div>
        <h2>{{ name }}</h2>
        <h2>{{ age }}</h2>
        <button @click="sayName">按钮</button>
      </div>
    </template>
    
    <script lang="ts">
    import { computed, reactive,toRefs } from "vue";
    
    interface DataProps {
      name: string;
      now: number;
      birthYear: number;
      age: number;
      sayName: () => void;
    }
    
    export default {
      name: "App",
      setup() {
       
    
        const data: DataProps = reactive({
          name: "zhangsan",
          birthYear: 2000,
          now: 2020,
          sayName: () => {
            console.log(1111);
            console.log(data.name);
            
            data.name = "I am " + data.name;
            console.log(data.name);
          },
          age: computed(() => {
            return data.now - data.birthYear;
          }),
        });
    
        const refData = toRefs(data)
        refData.age
        return {
          ...refData,
        };
      },
    };
    </script>
    
    <style>
    #app {
      font-family: Avenir, Helvetica, Arial, sans-serif;
      -webkit-font-smoothing: antialiased;
      -moz-osx-font-smoothing: grayscale;
      text-align: center;
      color: #2c3e50;
      margin-top: 60px;
    }
    </style>

    The above is the detailed content of How to solve the problems about ref and reactive in Vue3. For more information, please follow other related articles on the PHP Chinese website!

    Statement:
    This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete