上一篇VUE源码解析--数据监听原理中有几个思考问题,现在我们来解答一下第二个问题:
依赖到底指的是什么
谁使用到了数据,谁就是依赖 在vue中当数据改变时,会先通知依赖对应的Watcher实例,然后由Watcher实例去通知对应的视图进行更新 下面我们来结合代码详细讲解一下Watcher类
export default class Watcher {
// 定义了一些变量
vm: Component;
...
constructor (
vm: Component,
expOrFn: string | Function, // 这个地方是一个变量名或者是一个回调函数 -->具体查看$watch的用法
cb: Function,
options?: ?Object,
isRenderWatcher?: boolean
) {
this.vm = vm
...
this.value = this.lazy
? undefined
: this.get()
}
/**
* 实例化一个Watcher的时候回调用get方法
*/
get () {
// Dep.target = this
pushTarget(this)
let value
const vm = this.vm
try {
//调用getter 方法 为了收集依赖。通过dep.depend()方法 把 window.target中的值放到依赖数组中 ?????
value = this.getter.call(vm, vm)
} catch (e) {
if (this.user) {
handleError(e, vm, `getter for watcher "${this.expression}"`)
} else {
throw e
}
} finally {
// 把当前的this移出去
popTarget()
this.cleanupDeps()
}
return value
}
/**
* Add a dependency to this directive.
*/
addDep (dep: Dep) {
...
// 前面会有一些判断逻辑,可以自行查看源码这里只是关注主要流程
// 这个是把watcher对象添加到dep对象的sub中
dep.addSub(this)
}
/**
* Subscriber interface.
* Will be called when a dependency changes.
*/
update () {
// 更新视图
}