關(guān)于Vue源碼vm.$watch()內(nèi)部原理詳解
關(guān)于vm.$watch()詳細(xì)用法可以見(jiàn)官網(wǎng)。
大致用法如下:
<script> const app = new Vue({ el: "#app", data: { a: { b: { c: 'c' } } }, mounted () { this.$watch(function () { return this.a.b.c }, this.handle, { deep: true, immediate: true // 默認(rèn)會(huì)初始化執(zhí)行一次handle }) }, methods: { handle (newVal, oldVal) { console.log(this.a) console.log(newVal, oldVal) }, changeValue () { this.a.b.c = 'change' } } }) </script>
可以看到data屬性整個(gè)a對(duì)象被Observe, 只要被Observe就會(huì)有一個(gè)__ob__標(biāo)示(即Observe實(shí)例), 可以看到__ob__里面有dep,前面講過(guò)依賴(dep)都是存在Observe實(shí)例里面, subs存儲(chǔ)的就是對(duì)應(yīng)屬性的依賴(Watcher)。 好了回到正文, vm.$watch()在源碼內(nèi)部如果實(shí)現(xiàn)的。
內(nèi)部實(shí)現(xiàn)原理
// 判斷是否是對(duì)象 export function isPlainObject (obj: any): boolean { return _toString.call(obj) === '[object Object]' }
源碼位置: vue/src/core/instance/state.js
// $watch 方法允許我們觀察數(shù)據(jù)對(duì)象的某個(gè)屬性,當(dāng)屬性變化時(shí)執(zhí)行回調(diào) // 接受三個(gè)參數(shù): expOrFn(要觀測(cè)的屬性), cb, options(可選的配置對(duì)象) // cb即可以是一個(gè)回調(diào)函數(shù), 也可以是一個(gè)純對(duì)象(這個(gè)對(duì)象要包含handle屬性。) // options: {deep, immediate}, deep指的是深度觀測(cè), immediate立即執(zhí)行回掉 // $watch()本質(zhì)還是創(chuàng)建一個(gè)Watcher實(shí)例對(duì)象。 Vue.prototype.$watch = function ( expOrFn: string | Function, cb: any, options?: Object ): Function { // vm指向當(dāng)前Vue實(shí)例對(duì)象 const vm: Component = this if (isPlainObject(cb)) { // 如果cb是一個(gè)純對(duì)象 return createWatcher(vm, expOrFn, cb, options) } // 獲取options options = options || {} // 設(shè)置user: true, 標(biāo)示這個(gè)是由用戶自己創(chuàng)建的。 options.user = true // 創(chuàng)建一個(gè)Watcher實(shí)例 const watcher = new Watcher(vm, expOrFn, cb, options) if (options.immediate) { // 如果immediate為真, 馬上執(zhí)行一次回調(diào)。 try { // 此時(shí)只有新值, 沒(méi)有舊值, 在上面截圖可以看到undefined。 // 至于這個(gè)新值為什么通過(guò)watcher.value, 看下面我貼的代碼 cb.call(vm, watcher.value) } catch (error) { handleError(error, vm, `callback for immediate watcher "${watcher.expression}"`) } } // 返回一個(gè)函數(shù),這個(gè)函數(shù)的執(zhí)行會(huì)解除當(dāng)前觀察者對(duì)屬性的觀察 return function unwatchFn () { // 執(zhí)行teardown() watcher.teardown() } }
關(guān)于watcher.js。
源碼路徑: vue/src/core/observer/watcher.js
export default class Watcher { vm: Component; expression: string; cb: Function; id: number; deep: boolean; user: boolean; lazy: boolean; sync: boolean; dirty: boolean; active: boolean; deps: Array<Dep>; newDeps: Array<Dep>; depIds: SimpleSet; newDepIds: SimpleSet; before: ?Function; getter: Function; value: any; constructor ( vm: Component, // 組件實(shí)例對(duì)象 expOrFn: string | Function, // 要觀察的表達(dá)式 cb: Function, // 當(dāng)觀察的表達(dá)式值變化時(shí)候執(zhí)行的回調(diào) options?: ?Object, // 給當(dāng)前觀察者對(duì)象的選項(xiàng) isRenderWatcher?: boolean // 標(biāo)識(shí)該觀察者實(shí)例是否是渲染函數(shù)的觀察者 ) { // 每一個(gè)觀察者實(shí)例對(duì)象都有一個(gè) vm 實(shí)例屬性,該屬性指明了這個(gè)觀察者是屬于哪一個(gè)組件的 this.vm = vm if (isRenderWatcher) { // 只有在 mountComponent 函數(shù)中創(chuàng)建渲染函數(shù)觀察者時(shí)這個(gè)參數(shù)為真 // 組件實(shí)例的 _watcher 屬性的值引用著該組件的渲染函數(shù)觀察者 vm._watcher = this } vm._watchers.push(this) // options // deep: 當(dāng)前觀察者實(shí)例對(duì)象是否是深度觀測(cè) // 平時(shí)在使用 Vue 的 watch 選項(xiàng)或者 vm.$watch 函數(shù)去觀測(cè)某個(gè)數(shù)據(jù)時(shí), // 可以通過(guò)設(shè)置 deep 選項(xiàng)的值為 true 來(lái)深度觀測(cè)該數(shù)據(jù)。 // user: 用來(lái)標(biāo)識(shí)當(dāng)前觀察者實(shí)例對(duì)象是 開(kāi)發(fā)者定義的 還是 內(nèi)部定義的 // 無(wú)論是 Vue 的 watch 選項(xiàng)還是 vm.$watch 函數(shù),他們的實(shí)現(xiàn)都是通過(guò)實(shí)例化 Watcher 類完成的 // sync: 告訴觀察者當(dāng)數(shù)據(jù)變化時(shí)是否同步求值并執(zhí)行回調(diào) // before: 可以理解為 Watcher 實(shí)例的鉤子,當(dāng)數(shù)據(jù)變化之后,觸發(fā)更新之前, // 調(diào)用在創(chuàng)建渲染函數(shù)的觀察者實(shí)例對(duì)象時(shí)傳遞的 before 選項(xiàng)。 if (options) { this.deep = !!options.deep this.user = !!options.user this.lazy = !!options.lazy this.sync = !!options.sync this.before = options.before } else { this.deep = this.user = this.lazy = this.sync = false } // cb: 回調(diào) this.cb = cb this.id = ++uid // uid for batching this.active = true // 避免收集重復(fù)依賴,且移除無(wú)用依賴 this.dirty = this.lazy // for lazy watchers this.deps = [] this.newDeps = [] this.depIds = new Set() this.newDepIds = new Set() this.expression = process.env.NODE_ENV !== 'production' ? expOrFn.toString() : '' // 檢測(cè)了 expOrFn 的類型 // this.getter 函數(shù)終將會(huì)是一個(gè)函數(shù) if (typeof expOrFn === 'function') { this.getter = expOrFn } else { this.getter = parsePath(expOrFn) if (!this.getter) { this.getter = noop process.env.NODE_ENV !== 'production' && warn( `Failed watching path: "${expOrFn}" ` + 'Watcher only accepts simple dot-delimited paths. ' + 'For full control, use a function instead.', vm ) } } // 求值 this.value = this.lazy ? undefined : this.get() } /** * 求值: 收集依賴 * 求值的目的有兩個(gè) * 第一個(gè)是能夠觸發(fā)訪問(wèn)器屬性的 get 攔截器函數(shù) * 第二個(gè)是能夠獲得被觀察目標(biāo)的值 */ get () { // 推送當(dāng)前Watcher實(shí)例到Dep.target pushTarget(this) let value // 緩存vm const vm = this.vm try { // 獲取value value = this.getter.call(vm, vm) } catch (e) { if (this.user) { handleError(e, vm, `getter for watcher "${this.expression}"`) } else { throw e } } finally { // "touch" every property so they are all tracked as // dependencies for deep watching if (this.deep) { // 遞歸地讀取被觀察屬性的所有子屬性的值 // 這樣被觀察屬性的所有子屬性都將會(huì)收集到觀察者,從而達(dá)到深度觀測(cè)的目的。 traverse(value) } popTarget() this.cleanupDeps() } return value } /** * 記錄自己都訂閱過(guò)哪些Dep */ addDep (dep: Dep) { const id = dep.id // newDepIds: 避免在一次求值的過(guò)程中收集重復(fù)的依賴 if (!this.newDepIds.has(id)) { this.newDepIds.add(id) // 記錄當(dāng)前watch訂閱這個(gè)dep this.newDeps.push(dep) // 記錄自己訂閱了哪些dep if (!this.depIds.has(id)) { // 把自己訂閱到dep dep.addSub(this) } } } /** * Clean up for dependency collection. */ cleanupDeps () { let i = this.deps.length while (i--) { const dep = this.deps[i] if (!this.newDepIds.has(dep.id)) { dep.removeSub(this) } } //newDepIds 屬性和 newDeps 屬性被清空 // 并且在被清空之前把值分別賦給了 depIds 屬性和 deps 屬性 // 這兩個(gè)屬性將會(huì)用在下一次求值時(shí)避免依賴的重復(fù)收集。 let tmp = this.depIds this.depIds = this.newDepIds this.newDepIds = tmp this.newDepIds.clear() tmp = this.deps this.deps = this.newDeps this.newDeps = tmp this.newDeps.length = 0 } /** * Subscriber interface. * Will be called when a dependency changes. */ update () { /* istanbul ignore else */ if (this.lazy) { this.dirty = true } else if (this.sync) { // 指定同步更新 this.run() } else { // 異步更新隊(duì)列 queueWatcher(this) } } /** * Scheduler job interface. * Will be called by the scheduler. */ run () { if (this.active) { const value = this.get() // 對(duì)比新值 value 和舊值 this.value 是否相等 // 是對(duì)象的話即使值不變(引用不變)也需要執(zhí)行回調(diào) // 深度觀測(cè)也要執(zhí)行 if ( value !== this.value || // Deep watchers and watchers on Object/Arrays should fire even // when the value is the same, because the value may // have mutated. isObject(value) || this.deep ) { // set new value const oldValue = this.value this.value = value if (this.user) { // 意味著這個(gè)觀察者是開(kāi)發(fā)者定義的,所謂開(kāi)發(fā)者定義的是指那些通過(guò) watch 選項(xiàng)或 $watch 函數(shù)定義的觀察者 try { this.cb.call(this.vm, value, oldValue) } catch (e) { // 回調(diào)函數(shù)在執(zhí)行的過(guò)程中其行為是不可預(yù)知, 出現(xiàn)錯(cuò)誤給出提示 handleError(e, this.vm, `callback for watcher "${this.expression}"`) } } else { this.cb.call(this.vm, value, oldValue) } } } } /** * Evaluate the value of the watcher. * This only gets called for lazy watchers. */ evaluate () { this.value = this.get() this.dirty = false } /** * Depend on all deps collected by this watcher. */ depend () { let i = this.deps.length while (i--) { this.deps[i].depend() } } /** * 把Watcher實(shí)例從從當(dāng)前正在觀測(cè)的狀態(tài)的依賴列表中移除 */ teardown () { if (this.active) { // 該觀察者是否激活狀態(tài) if (!this.vm._isBeingDestroyed) { // _isBeingDestroyed一個(gè)標(biāo)識(shí),為真說(shuō)明該組件實(shí)例已經(jīng)被銷毀了,為假說(shuō)明該組件還沒(méi)有被銷毀 // 將當(dāng)前觀察者實(shí)例從組件實(shí)例對(duì)象的 vm._watchers 數(shù)組中移除 remove(this.vm._watchers, this) } // 當(dāng)一個(gè)屬性與一個(gè)觀察者建立聯(lián)系之后,屬性的 Dep 實(shí)例對(duì)象會(huì)收集到該觀察者對(duì)象 let i = this.deps.length while (i--) { this.deps[i].removeSub(this) } // 非激活狀態(tài) this.active = false } } }
export const unicodeRegExp = /a-zA-Z\u00B7\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u037D\u037F-\u1FFF\u200C-\u200D\u203F-\u2040\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD/ const bailRE = new RegExp(`[^${unicodeRegExp.source}.$_\\d]`) // path為keypath(屬性路徑) 處理'a.b.c'(即vm.a.b.c) => a[b[c]] export function parsePath (path: string): any { if (bailRE.test(path)) { return } const segments = path.split('.') return function (obj) { for (let i = 0; i < segments.length; i++) { if (!obj) return obj = obj[segments[i]] } return obj } }
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
vue點(diǎn)擊按鈕實(shí)現(xiàn)簡(jiǎn)單頁(yè)面的切換
這篇文章主要為大家詳細(xì)介紹了vue點(diǎn)擊按鈕實(shí)現(xiàn)簡(jiǎn)單頁(yè)面的切換,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-09-09Vue?動(dòng)態(tài)路由的實(shí)現(xiàn)詳情
這篇文章主要介紹了Vue?動(dòng)態(tài)路由的實(shí)現(xiàn),動(dòng)態(tài)路由是一個(gè)常用的功能,根據(jù)后臺(tái)返回的路由json表,前端動(dòng)態(tài)顯示可跳轉(zhuǎn)的路由項(xiàng),本文主要實(shí)現(xiàn)的是后臺(tái)傳遞路由,前端拿到并生成側(cè)邊欄的一個(gè)形勢(shì),需要的朋友可以參考一下2022-06-06vue3中路由傳參query、params及動(dòng)態(tài)路由傳參詳解
vue3中的傳參方式和vue2中一樣,都可以用query和params傳參,下面這篇文章主要給大家介紹了關(guān)于vue3中路由傳參query、params及動(dòng)態(tài)路由傳參的相關(guān)資料,需要的朋友可以參考下2022-09-09vue清空數(shù)組的幾個(gè)方式(小結(jié))
本文主要介紹了vue清空數(shù)組的幾個(gè)方式,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-12-12vue項(xiàng)目中實(shí)現(xiàn)緩存的最佳方案詳解
這篇文章主要給大家介紹了關(guān)于vue項(xiàng)目中實(shí)現(xiàn)緩存的最佳方案,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用vue具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07vue.js根據(jù)代碼運(yùn)行環(huán)境選擇baseurl的方法
本篇文章主要介紹了vue.js根據(jù)代碼運(yùn)行環(huán)境選擇baseurl的方法,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-02-02