Home > Web Front-end > Vue.js > How to use toRef and toRefs in Vue3

How to use toRef and toRefs in Vue3

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2023-05-11 21:28:04
forward
1179 people have browsed it

toRef, as the name suggests, is not ref responsive data. Convert it to ref responsive data.

Easy to understand:

 <template>
  <h4>姓名:{{ person.name }}</h4>
  <h4>年龄:{{ person.age }}</h4>
  <h4>薪资:{{ person.job.j1.salary }}</h4>
  <button @click="person.name += &#39;!&#39;">修改姓名</button>
  <button @click="person.age++">增长年龄</button>
  <button @click="person.job.j1.salary++">涨薪</button>
</template>
 
<script>
import { reactive } from "vue";
export default {
  setup() {
    let person = reactive({
      name: "张三",
      age: 18,
      job: {
        j1: {
          salary: 20,
        },
      },
    });
    return {
      person,
    };
  },
};
</script>
 
<style>
</style>
Copy after login

It’s okay to implement the function first, then consider the code Optimization:

How to use toRef and toRefs in Vue3

Then you may think that when I return, it will be more troublesome,

 return {
      name: person.name,
      age: person.age,
      job: person.job.j1.salary,
    };
Copy after login

However, if you do this, you will find that the page is not responsive. The data modification page does not change, as follows:

How to use toRef and toRefs in Vue3

## Let’s look at the usage of toRef: It is obvious that the effect is achieved

 <template>
  <h4>姓名:{{ name }}</h4>
  <h4>年龄:{{ age }}</h4>
  <h4>薪资:{{ salary }}</h4>
  <button @click="name += &#39;!&#39;">修改姓名</button>
  <button @click="age++">增长年龄</button>
  <button @click="salary++">涨薪</button>
</template>
 
<script>
import { reactive, toRef } from "vue";
export default {
  setup() {
    let person = reactive({
      name: "张三",
      age: 18,
      job: {
        j1: {
          salary: 20,
        },
      },
    });
    return {
      name: toRef(person, "name"),
      age: toRef(person, "age"),
      salary: toRef(person.job.j1, "salary"),
    };
  },
};
</script>
 
<style>
</style>
Copy after login

How to use toRef and toRefs in Vue3

After introducing the usage of toRef, let’s take a look at the usage of toRefs

How to use toRef and toRefs in Vue3

The above is the detailed content of How to use toRef and toRefs in Vue3. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template