Home >Web Front-end >Vue.js >How to use toRef and toRefs in Vue3
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 += '!'">修改姓名</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>
It’s okay to implement the function first, then consider the code Optimization:
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, };
However, if you do this, you will find that the page is not responsive. The data modification page does not change, as follows:
## 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 += '!'">修改姓名</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>After introducing the usage of toRef, let’s take a look at the usage of toRefs
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!