toRef
-
作用:创建一个 ref 对象,其value值指向另一个对象中的某个属性。
-
语法:
const name = toRef(person,'name')
-
应用: 要将响应式对象中的某个属性单独提供给外部使用时。
-
扩展:
toRefs
与toRef
功能一致,但可以批量创建多个 ref 对象,语法:toRefs(person)
Demo5.vue
<template> {{person}} <h2>姓名:{{name}}</h2> <h2>年龄:{{age}}</h2> <h2>薪资:{{salary}}</h2> <button @click="name+= '!' ">修改姓名</button> <button @click="age++">增长年龄</button> <button @click="salary++">涨薪</button> </template> <script> import {ref,reactive,toRef} from 'vue' export default { name: 'Demo', setup() { let person = reactive({ name:'张三', age:18, job:{ j1:{ salary:20 } } }) let name = toRef(person,'name') let age = toRef(person,'age') let salary = toRef(person.job.j1,'salary') return{person,name,age,salary} } } </script> <style> </style>
toRefs写法
<template> {{person}} <h2>姓名:{{name}}</h2> <h2>年龄:{{age}}</h2> <h2>薪资:{{job.j1.salary}}</h2> <button @click="name+= '!' ">修改姓名</button> <button @click="age++">增长年龄</button> <button @click="job.j1.salary++">涨薪</button> </template> <script> import {ref,reactive,toRefs} from 'vue' export default { name: 'Demo', setup() { let person = reactive({ name:'张三', age:18, job:{ j1:{ salary:20 } } }) return{ person, //name:toRef(person,'name'), //age:toRef(person,'age'), //name:toRef(person,'name') , //salary:toRef(person.job.j1,'salary') , ...toRefs(person) } } } </script> <style> </style>
标签:salary,函数,age,toRefs,toRef,person,name From: https://www.cnblogs.com/ixtao/p/17542626.html