關(guān)于Vue源碼vm.$watch()內(nèi)部原理詳解
關(guān)于vm.$watch()詳細(xì)用法可以見官網(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對象被Observe, 只要被Observe就會(huì)有一個(gè)__ob__標(biāo)示(即Observe實(shí)例), 可以看到__ob__里面有dep,前面講過依賴(dep)都是存在Observe實(shí)例里面, subs存儲(chǔ)的就是對應(yīng)屬性的依賴(Watcher)。 好了回到正文, vm.$watch()在源碼內(nèi)部如果實(shí)現(xiàn)的。
內(nèi)部實(shí)現(xiàn)原理
// 判斷是否是對象
export function isPlainObject (obj: any): boolean {
return _toString.call(obj) === '[object Object]'
}
源碼位置: vue/src/core/instance/state.js
// $watch 方法允許我們觀察數(shù)據(jù)對象的某個(gè)屬性,當(dāng)屬性變化時(shí)執(zhí)行回調(diào)
// 接受三個(gè)參數(shù): expOrFn(要觀測的屬性), cb, options(可選的配置對象)
// cb即可以是一個(gè)回調(diào)函數(shù), 也可以是一個(gè)純對象(這個(gè)對象要包含handle屬性。)
// options: {deep, immediate}, deep指的是深度觀測, immediate立即執(zhí)行回掉
// $watch()本質(zhì)還是創(chuàng)建一個(gè)Watcher實(shí)例對象。
Vue.prototype.$watch = function (
expOrFn: string | Function,
cb: any,
options?: Object
): Function {
// vm指向當(dāng)前Vue實(shí)例對象
const vm: Component = this
if (isPlainObject(cb)) {
// 如果cb是一個(gè)純對象
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í)只有新值, 沒有舊值, 在上面截圖可以看到undefined。
// 至于這個(gè)新值為什么通過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)前觀察者對屬性的觀察
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í)例對象
expOrFn: string | Function, // 要觀察的表達(dá)式
cb: Function, // 當(dāng)觀察的表達(dá)式值變化時(shí)候執(zhí)行的回調(diào)
options?: ?Object, // 給當(dāng)前觀察者對象的選項(xiàng)
isRenderWatcher?: boolean // 標(biāo)識(shí)該觀察者實(shí)例是否是渲染函數(shù)的觀察者
) {
// 每一個(gè)觀察者實(shí)例對象都有一個(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í)例對象是否是深度觀測
// 平時(shí)在使用 Vue 的 watch 選項(xiàng)或者 vm.$watch 函數(shù)去觀測某個(gè)數(shù)據(jù)時(shí),
// 可以通過設(shè)置 deep 選項(xiàng)的值為 true 來深度觀測該數(shù)據(jù)。
// user: 用來標(biāo)識(shí)當(dāng)前觀察者實(shí)例對象是 開發(fā)者定義的 還是 內(nèi)部定義的
// 無論是 Vue 的 watch 選項(xiàng)還是 vm.$watch 函數(shù),他們的實(shí)現(xiàn)都是通過實(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í)例對象時(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ù)依賴,且移除無用依賴
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()
: ''
// 檢測了 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ā)訪問器屬性的 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á)到深度觀測的目的。
traverse(value)
}
popTarget()
this.cleanupDeps()
}
return value
}
/**
* 記錄自己都訂閱過哪些Dep
*/
addDep (dep: Dep) {
const id = dep.id
// newDepIds: 避免在一次求值的過程中收集重復(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()
// 對比新值 value 和舊值 this.value 是否相等
// 是對象的話即使值不變(引用不變)也需要執(zhí)行回調(diào)
// 深度觀測也要執(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è)觀察者是開發(fā)者定義的,所謂開發(fā)者定義的是指那些通過 watch 選項(xiàng)或 $watch 函數(shù)定義的觀察者
try {
this.cb.call(this.vm, value, oldValue)
} catch (e) {
// 回調(diào)函數(shù)在執(zhí)行的過程中其行為是不可預(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)前正在觀測的狀態(tài)的依賴列表中移除
*/
teardown () {
if (this.active) {
// 該觀察者是否激活狀態(tài)
if (!this.vm._isBeingDestroyed) {
// _isBeingDestroyed一個(gè)標(biāo)識(shí),為真說明該組件實(shí)例已經(jīng)被銷毀了,為假說明該組件還沒有被銷毀
// 將當(dāng)前觀察者實(shí)例從組件實(shí)例對象的 vm._watchers 數(shù)組中移除
remove(this.vm._watchers, this)
}
// 當(dāng)一個(gè)屬性與一個(gè)觀察者建立聯(lián)系之后,屬性的 Dep 實(shí)例對象會(huì)收集到該觀察者對象
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
}
}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
vue中el-select中多選回顯數(shù)據(jù)后沒法重新選擇和更改的解決
本文主要介紹了vue中el-select中多選回顯數(shù)據(jù)后沒法重新選擇和更改解決,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-01-01
Vue?通過this.$emit()方法子組件向父組件傳值(步驟分享)
這篇文章主要介紹了Vue?this.$emit()方法通過子組件向父組件傳值,第一步在父組件中引入子組件,第二步子組件向父組件傳值,本文通過需要的朋友可以參考下2022-11-11
解決vue項(xiàng)目中前后端交互的跨域問題、nginx代理配置方式
這篇文章主要介紹了解決vue項(xiàng)目中前后端交互的跨域問題、nginx代理配置方式,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-09-09
vue+element使用動(dòng)態(tài)加載路由方式實(shí)現(xiàn)三級菜單頁面顯示的操作
這篇文章主要介紹了vue+element使用動(dòng)態(tài)加載路由方式實(shí)現(xiàn)三級菜單頁面顯示的操作,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-08-08
Element?el-date-picker?日期選擇器的使用
本文主要介紹了Element?el-date-picker?日期選擇器的使用,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-04-04
vue3點(diǎn)擊按鈕下載文件功能的代碼實(shí)現(xiàn)
在寫vue項(xiàng)目時(shí),有個(gè)需求是點(diǎn)擊表格中某一行的下載按鈕,然后開始下載這一行對應(yīng)的文件,所以本文小編給大家介紹了使用vue3實(shí)現(xiàn)點(diǎn)擊按鈕下載文件功能,文中有詳細(xì)的代碼示例供大家參考,需要的朋友可以參考下2024-01-01

