toRef
作用:创建一个ref对象,其value值指向另一个对象中的某个属性。
语法:const name = toRef(person, 'name');
应用:要将响应式对象中的某个属性单独提供给外部使用时
扩展:toRefs与toRef功能一致,但可以批量创建多个ref对象,语法:toRefs(person)
具体案例代码如下:
<template>
<div>{{ name }}</div>
<button @click="name += '~'">按钮name</button>
<div>{{ salary }}</div>
<button @click="salary++">按钮salary</button>
<!-- toRefs使用多层次结构的,只能这样写 -->
<!-- <div>{{ job.j1.salary }}</div>
<button @click="job.j1.salary++">按钮salary</button> -->
</template>
<script>
import { reactive, toRefs } from 'vue'
export default {
name: 'DemoComponent',
setup() {
let person = reactive({
name: '张三',
job: {
j1: {
salary: 20
}
}
})
// 使用ref时界面能更新但是person的数据没更新, 因此不能使用ref
// return {
// name: ref(person.name),
// salary: ref(person.job.j1.salary)
// }
// 使用toRef能解决person没更新问题
// toRef(person)返回的是RefImpl对象
// return {
// name: toRef(person, 'name'),
// salary: toRef(person.job.j1, 'salary')
// }
// 使用toRefs只能可以处理对象第一层的问题
return {
...toRefs(person)
}
}
}
</script>
Vue3:toRef和toRefs
于 2023-12-13 13:50:59 首次发布