Vue中Watch的初始化流程
- initWatch
- 遍历watch中的每一个watch函数,执行createWatcher,createWatcher有两个作用:获取到watch监听的回调和调用
vm.$watch
- 执行
vm.$watch
,这个函数主要也是两个功能,判断是否是立即执行的监听回调,如果需要立即执行,那就将回调(也就是watch的handler
)立即执行一遍。第二个功能是给每一个watch分配一个Watcher。 - 主要来分析一下,新建这个Watcher的过程都做了些什么。
var Watcher = function (vm, key, cb, opt) {
this.vm = vm;
this.deep = opt.deep;
this.cb = cb;
// 这里省略处理 xx.xx.xx 这种较复杂的key
this.getter = function(obj) {
return obj[key]
};
// this.get 作用就是执行 this.getter函数
this.value = this.get();
};
Watcher.prototype.get = function() {
// 这个getter会去实例上根据相应的key,读取相应的值,并保存在`this.value`上
var value = this.getter(this.vm);
// 如果设置了深度监听,那么会进行深度遍历
if (this.deep) traverse(value);
return value
};