Vue3ts To全家桶 toRef toRaw toRefs

to全家桶

toRef

这玩意没啥用,只不过toRefs是用它实现的
toRef传入的第一个参数必须是相应式对象,如果传入的是非响应式对象,那么不会触发视图更新,屌用没有
传入非响应式对象后log输出看起来是RefImpl对象,但是其中没有进行响应式处理

    import {reactive,readonly,ref,toRef} from 'vue'

    type Person = {
        name:{
            firstname:string,
            lastname:string
        },
        age:number
    }

    const zhouzhou = reactive<Person>({
        name:{
            firstname:'zhou',
            lastname:'qi'
        },
        age:23
    })
    
    //toRef传入两个参数,第一个是一个对象,第二个是这个对象的key值
    const name = toRef(zhouzhou,'name')
    
    const handleTest = () =>{
        //这里我们可以通过name来修改,会引发页面视图更新
        name.value.firstname = 'qqqq'
    }

toRefs

如果不使用toRefs,那么相应式对象解构取值后会丢失相应式,所以我们使用toRefs来对相应式对象进行解构取值

toRefs不能解构深层结构

简单实现toRefs源码

import {reactive,readonly,ref,toRef} from 'vue'

type Person = {
  name:{
    firstname:string,
    lastname:string
  },
  age:number
}

const zhouzhou = reactive<Person>({
  name:{
    firstname:'zhou',
    lastname:'qi'
  },
  age:23
})
//自己实现toRefs
const toRefs = <T extends object>(obj:T)=>{
          const map:any = {}
          for(let key in obj){
            console.log(key);
            map[key] = toRef(obj,key)
          }
          return map
        }
const {name,age} = toRefs(zhouzhou)
        
const handleTest = () =>{
          name.value = {
            firstname : '11',
            lastname : '222'
          }
          age.value = 3232
}

toRaw

将其解构为原始对象
![image.png](https://img-blog.csdnimg.cn/img_convert/9f7fd6aeb0c677822afd7e64c8526cae.png#clientId=u5acfeba5-eac8-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=90&id=u2fbcaf14&margin=[object Object]&name=image.png&originHeight=90&originWidth=225&originalType=binary&ratio=1&rotation=0&showTitle=false&size=4473&status=done&style=none&taskId=u1dd8c0d1-6e59-4674-8f96-b62d0b6ff91&title=&width=225)

 import {reactive, readonly, ref, toRefs, toRaw} from 'vue'

    type Person = {
        name: {
            firstname: string,
            lastname: string
        },
        age: number
    }

    const zhouzhou = reactive<Person>({
        name: {
            firstname: 'zhou',
            lastname: 'qi'
        },
        age: 23
    })
    const zhou = toRaw(zhouzhou)
    console.log(zhou);

参考:https://blog.csdn.net/qq1195566313

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值