Home  >  Article  >  Web Front-end  >  How to solve the failure of Vue3 ref to build responsive variables

How to solve the failure of Vue3 ref to build responsive variables

PHPz
PHPzforward
2023-05-13 10:43:111292browse

vue3 ref fails to construct a responsive variable

Problem description

Use ref to declare a responsive variable in Vue3, and use a function to change the value, but the value cannot be changed responsively

<template>
  <p>{{userName}}</p>
  <button @click=&#39;change()&#39;>change</button>
</template>

<script>
  //引入定义响应式数据的函数
  import {reactive} from &#39;vue&#39;;
  import {ref} from "@vue/reactivity"; //!!!!!注意,这里有个坑,ref必须是引用自vue,而非@vue/reactivity
  export default {
  name: &#39;App&#39;,
  //为Vue3的新特性提供统一入口,代码都会在这个函数中添加
  //在beforecreated之前进行,因此无法访问this,亦即无法访问data和method
  setup(){
    //定义响应式数据:数据变化,模板中渲染会自动刷新
    // const obj=reactive({
    //   userName:&#39;jack&#39;,
    // });
    //只定义一个变量,可以使用ref将变量定义为响应式
    let userName=ref(&#39;jack&#39;)
    console.log(userName);
    const change=()=> {
      userName.value=&#39;rose&#39;     //注意修改的是ref对象的value属性,但是在template中使用的时候不需要再加value
      console.log(userName);
    }

    return {userName,change}
  },
}
</script>

Solution

I don’t know why, when the reference is

import {ref} from "@vue/reactivity"

, there will be no response, but you only need to change it to

import {ref} from "vue"

vue3 Responsive API ref and reactive

We know that the ref function and the reactive function are used to achieve data responsiveness. But how to choose between ref and reactive in development? Let’s talk about the difference between ref and reactive.

Review

Before the Vue3 version, the response data was defined in the data function

<template>
  <h2>{{ title }}</h2>
</template>
 
<script>
  export default {
    data() {
      return {
        title: "Hello, Vue!"
      };
    }
  };
</script>

Vue2 will traverse all properties in data and use Object.defineProperty to convert each property Convert to getter/setter, getter is used to collect dependencies, and setter is used to execute notify and publish update events.

Vue2 creates a Dep object for each property as an intermediary in the subscription-publish model to collect dependencies. Vue tracks these dependencies and notifies changes when they are accessed and modified.

Vue3

Vue3 introduces ref and reactive to create responsive data:

<template>
  <h2>{{ title }}</h2>
  <h3>{{ data.author }}</h3>
  <button @click=""changeTitle>修改title</button>
</template>
 
<script>
  import { ref, reactive, toRefs } from "vue";
  export default {
    setup() {
      const title = ref("Hello, Vue 3!");
      // 修改
      function changeTitle(){
        title.value == "Hello, Vue3!"
      }
 
      const data = reactive({
        author: "青年码农",
        age: "18"
      });
 
      return { title, data, changeTitle };
    }
  };
</script>

We can probably see the difference from the above code. The function of ref is to convert a primitive data type into a responsive data. There are 7 primitive data types, namely: String, Number, BigInt, Boolean, Symbol, Undefined, and Null. But there is a weird trick, that is, ref can also be an object. We’ll talk about it later. The function of reactive is to convert an object into a responsive object.

  • ref: The function of

ref is to convert a primitive data type into a data type with response The data type of the formula attribute.

const title = ref("Hello, Vue 3!");

ref receives the parameter and returns it wrapped in an object with a value attribute. This attribute can then be used to access or change the value of the responsive variable. For example, in the above code we use count. value to modify the value, as follows:

title.value = "Hello, Vue3!"

As mentioned above, ref can also accept object types

const data = ref({
    author: "青年码农",
    age: "18"
});

This is also possible, but it will be a bit awkward when assigning values.

data.value.author = "nmgwap";

ref The reactive principle relies on Object.defineProperty(), so if it is an object, it is recommended to use reactive.

How to solve the failure of Vue3 ref to build responsive variables

  • reactive:

reactive Returns the reactivity of the object copy, which will unpack all deep refs while maintaining the responsiveness of the refs. Generally we use it to implement the responsiveness of objects or arrays.

const data = reactive({
    author: "青年码农",
    age: "18"
});

There is no difference between modification and ordinary objects, the view will be updated in real time

data.author = "nmgwap"

Note:

ref is for original data type and reactive Both APIs are used for objects to give reactivity to common JavaScript data types.

The above is the detailed content of How to solve the failure of Vue3 ref to build responsive variables. 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