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