toRef
非响应式对象用toRef啥用都没有 只适用于响应式对象
通常用于 需要传响应式对象时的转化
- 例如: let name = man.name 此时name是非响应式的 let name = toRef(man,'name') 此时name是响应式的
<template>
<div>
{{man}}
</div>
<button @click="change">改名</button>
</template>
<script setup lang='ts'>
import { ref , reactive, shallowReactive, toRef } from 'vue'
const man =reactive( {
name:'rpz',
age:23,
hobby:'lol'
})
const like = toRef(man,'name')
const change = () => {
like.value = 'g'
}
</script>
源码
function toRef<T extends object,K extends keyof T>(
object:T,
key:K,
defaultValue?:T[K]
):ToRef<T[K]>{
const val = object[key] //先存对应值
//判断val是否是ref 是直接返回 不是就new一个ref
return isRef(val)?val:(new ObjectRefImpl(object,key,defaultValue) as any)
}
ObjectRefImpl与 RefImpl的区别在于 没有收集依赖、触发依赖更新 因此对于非响应式无效 而对响应式对象,其自带了以上功能
toRefs
手写toRefs
const toRefs = <T extends object> (obj:T) => {
const map = {}
for(let key in obj){
map[key] = toRef(obj,key)
}
return map
}
解构用法
当你想要结构reactive时 一般要用toRefs来解构
let {name,age} = toRefs(man)
//此时name和age都为响应式
toRaw
const change = () => {
console.log(man,toRaw(man));
//相当于 console.log(man,man['__v_raw']);
console.log(toRaw(man)==man['__v_raw']); //true
}
//打印出一个响应式 一个普通对象
\