toRef与toRefs

作用:

创建一个ref对象,其value值指向另一个对象中的某个属性

语法:

const name=toRef(person,”name”)

应用:

要将响应式对象中的某个属性单独提供给外部使用时

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<template>
<h2>姓名:{{name}}</h2>
<h2>年龄:{{age}}</h2>
<h2>薪资:{{salary}}</h2>
<button @click="name+='~'">修改姓名</button>
<button @click="age++">增长年龄</button>
<button @click="salary++">涨薪</button>
</template>
<script>
import {reactive,toRef} from 'vue'
export default {
name: "Demo",
setup(){
let person=reactive({
name:'张三',
age:20,
job:{
j1:{
salary:20
}
}
})



return {
//第一个参数传递一个对象即可
name:toRef(person,'name'),
age:toRef(person,'age'),
salary:toRef(person.job.j1,'salary')
}
},
}
</script>

<style scoped>

</style>

扩展

toRefs与toRef功能一致,但可以批量创建多个ref对象,语法:toRefs(person)

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<template>
<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 {reactive,toRefs} from 'vue'
export default {
name: "Demo",
setup(){
let person=reactive({
name:'张三',
age:20,
job:{
j1:{
salary:20
}
}
})



return toRefs(person)
},
}
</script>

<style scoped>

</style>