toRef与toRefs函数

toRef

  • 作用:创建一个 ref 对象,其value值指向另一个对象中的某个属性。

  • 语法:const name = toRef(person,'name')

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

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

 

Demo5.vue

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
39
40
<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写法

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
39
40
41
42
43
<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>

  

 

posted @   iTao0128  阅读(61)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
点击右上角即可分享
微信分享提示