Vue 2.0 侦听器 watch属性代码详解(2)

Watcher.prototype.get = function get () { //第3135行 pushTarget(this); //将当前用户watch保存到Dep.target总=中 var value; var vm = this.vm; try { value = this.getter.call(vm, vm); //执行用户wathcer的getter()方法,此方法会将当前用户watcher作为订阅者订阅起来 } 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) { traverse(value); } popTarget(); //恢复之前的watcher this.cleanupDeps(); } return value };

当我们点击按钮了修改了app.message时就会执行app.message对应的访问控制器的set()方法,就会执行这个用户watcher的update()方法,如下:

Watcher.prototype.update = function update () { //第3200行 更新Watcher /* istanbul ignore else */ if (this.lazy) { this.dirty = true; } else if (this.sync) { //如果$this.sync为true,则直接运行this.run获取结果 this.run(); } else { queueWatcher(this); //否则调用queueWatcher()函数把所有要执行update()的watch push到队列中 } }; Watcher.prototype.run = function run () { //第3215行 执行,会调用get()获取对应的值 if (this.active) { var value = this.get(); 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 var oldValue = this.value; this.value = value; if (this.user) { //如果是个用户 watcher try { this.cb.call(this.vm, value, oldValue); //执行这个回调函数 vm作为上下文 参数1为新值 参数2为旧值     也就是最后我们自己定义的function(newval,val){ console.log(newval,val) }函数 } catch (e) { handleError(e, this.vm, ("callback for watcher \"" + (this.expression) + "\"")); } } else { this.cb.call(this.vm, value, oldValue); } } } };

对于侦听器来说,Vue内部的流程就是这样子

总结

以上所述是小编给大家介绍的Vue 2.0 侦听器 watch属性代码详解,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/83f0c6f13dee8164b8cbe1f9da6279e4.html