get () {
pushTarget(this) // 设置 Dep.target 为本watcher
let value
const vm = this.vm
try {
value = this.getter.call(vm, vm) // 触发已定义data或者props的getter依赖收集
} 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) { // 有deep属性就深度遍历
traverse(value)
}
popTarget() // 依赖收集完毕,出栈
this.cleanupDeps() // 转移watcher最新newDeps到deps上
}
return value
}
这个get,会执行 this.getter.call(vm,vm)。
由于当前的props, datas 已经都响应式了,这样会触发他们的get进行依赖收集
Object.defineProperty(obj, key, {
// ...
get: function reactiveGetter () {
const value = getter ? getter.call(obj) : val
if (Dep.target) {
dep.depend()
// ...
}
return value
},
// ...
}
// dep.js
depend () {
if (Dep.target) {
Dep.target.addDep(this) // 目标把自己添加为依赖项
}
}
// watcher.js
// newDeps: Array<Dep>;
// depIds: SimpleSet;
// newDepIds: SimpleSet;
addDep (dep: Dep) {
const id = dep.id
if (!this.newDepIds.has(id)) {
this.newDepIds.add(id)
this.newDeps.push(dep)
if (!this.depIds.has(id)) { // 第一次并没有
dep.addSub(this) // 传进来的依赖,添加本watcher订阅
}
}
}
// dep.js
addSub (sub: Watcher) {
this.subs.push(sub) // 设置订阅的watcher
}