reactive定義是通過createReactiveObject方法實現的糟红,以下簡述其內容
1.判斷傳入的值媳否,如果不是object類型的棵逊,直接返回當前值
if (!isObject(target)) {
if (__DEV__) {
console.warn(`value cannot be made reactive: ${String(target)}`)
}
return target
}
示例如下:
const notObj = reactive(1)
console.log(notObj) // 1 警告:value cannot be made reactive: 1
2.如果傳入的值已經進行proxy代理,并且不是只讀的reactive對象唬渗,直接返回當前值
if (
target[ReactiveFlags.RAW] &&
!(isReadonly && target[ReactiveFlags.IS_REACTIVE])
) {
return target
}
示例如下:
import { reactive } from 'vue';
const obj = { a: 1}
const reactiveVal1 = reactive(obj)
const reactiveVal2 = reactive(reactiveVal1)
console.log(reactiveVal1 === reactiveVal2) // true
3.如果proxyMap映射中已經存在該對象的proxy映射乐导,則直接返回之前映射的內容
const existingProxy = proxyMap.get(target)
if (existingProxy) {
return existingProxy
}
示例如下:
import { reactive } from 'vue';
const obj = { a: 1}
const reactiveVal1 = reactive(obj)
const reactiveVal2 = reactive(obj)
console.log(reactiveVal1 === reactiveVal2) // true
4.一些特殊的值是不能進行proxy代理的,如日期浸颓、正則物臂、promise,直接返回傳入的值
const targetType = getTargetType(target)
if (targetType === TargetType.INVALID) {
return target
}
示例如下:
const date = new Date()
const notAllowObj = reactive(date)
console.log(notAllowObj) // Wed Feb 01 2023 20:15:33 GMT+0800 (中國標準時間)
5.其他對象产上,Array/Object通過baseHandlers對象進行代理棵磷,
Map/Set/WeakMap/WeakSet通過collectionHandlers對象進行代理
const proxy = new Proxy(
target,
targetType === TargetType.COLLECTION ? collectionHandlers : baseHandlers
)
proxyMap.set(target, proxy)
return proxy
下文則繼續(xù)對本文中提到的baseHandlers對象進行展開!
本人菜雞晋涣,有問題望前輩及時指出仪媒,不勝感激!谢鹊!