Vue3 0 響應式原理的剖析(開課吧公開課)

2021-10-21 00:27:50 字數 3632 閱讀 1915

const toproxy =

newweakmap()

// 形如 obj: observed

const toraw =

newweakmap()

// 形如 observed: obj

function

isobject

(obj)

function

reactive

(obj)

// obj 本身是乙個 proxy

if(toraw.

has(obj)

)// **物件

const observed =

newproxy

(obj,:$

`)return

isobject

(res)

?reactive

(res)

: res

},set

(target, key, value, reciever):$

`)return res

},deleteproperty

(target, key)`)

return res

}})// 快取

toproxy.

set(obj, observed)

toraw.

set(observed, obj)

return observed

}

const toproxy =

newweakmap()

const toraw =

newweakmap()

function

isobject

(obj)

function

reactive

(obj)

// obj 本身是乙個 proxy

if(toraw.

has(obj)

)// **物件

const observed =

newproxy

(obj,:$

`)// 依賴收集

track

(target, key)

return

isobject

(res)

?reactive

(res)

: res

},set

(target, key, value, reciever):$

`)return res

},deleteproperty

(target, key)`)

return res

}})// 快取

toproxy.

set(obj, observed)

toraw.

set(observed, obj)

return observed

}const activereactiveeffectstack =

// 依賴收集的執行

// 基本結構 }

const targetsmap =

newweakmap()

function

track

(target, key)

// 存放 key

let deps = depsmap.

get(key)if(

!deps)if(

!deps.

has(effect))}

}function

effect

(fn)

catch

(error

)finally

}rxeffect()

// 預設立即執行

return rxeffect

}

const

=require

('async_hooks'

)const toproxy =

newweakmap()

const toraw =

newweakmap()

function

isobject

(obj)

function

reactive

(obj)

// obj 本身是乙個 proxy

if(toraw.

has(obj)

)// **物件

const observed =

newproxy

(obj,:$

`)// 依賴收集

track

(target, key)

return

isobject

(res)

?reactive

(res)

: res

},set

(target, key, value, reciever):$

`)trigger

(target,

'add'

, key)

}else

if(oldval !== value):$

`)trigger

(target,

'set'

, key)

}return res

},deleteproperty

(target, key)`)

trigger

(target,

'delete'

, key)

}return res

}})// 快取

toproxy.

set(obj, observed)

toraw.

set(observed, obj)

return observed

}const activereactiveeffectstack =

// 依賴收集的執行

// 基本結構 }

const targetsmap =

newweakmap()

function

track

(target, key)

// 存放 key

let deps = depsmap.

get(key)if(

!deps)if(

!deps.

has(effect))}

}function

hasown

(obj, key)

function

trigger

(target, type, key))}

}// 陣列新增或刪除

if(type ===

'add'

|| type ===

'delete'))

}}}// 獲取已存在的 dep set 執行

effects.

foreach

((effect)

=>

effect()

)}function

effect

(fn)

catch

(error

)finally

}rxeffect()

// 預設立即執行

return rxeffect

}

手寫Vue3 0響應式原理

vue3.0 響應式原理 const toproxy new weakmap 放置的是 原物件 過的物件 防止多次 同乙個物件 const toraw new weakmap 放置的是 過的物件 原物件 防止 已經 過的物件 判斷是否為物件 function isobject val 判斷key是否...

vue3 0 響應式工具集

使用 import from vue 1 unref 判斷是否是ref物件,是返回ref物件.value值,不是返回引數本身 語法糖 val isref val val.value val const xx unref x 2 readonly 接受乙個物件 reactive響應式或js純物件 或r...

Vue3 0 響應式系統(一)

vue3.0 對響應式系統模組進行重構,不再用object.defineproperty了,而是改用proxy。這樣做大體上有兩個好處,一是不用對陣列進行單獨處理了,去掉了vue.set 和 vue.delete介面,因為proxy可以對整個物件進行攔截操作。二是對原始物件資料變為響應式物件資料時不...