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

--------------------------------------------------------------------------------

先来看看官网的介绍:

官网介绍的很好理解了,也就是监听一个数据的变化,当该数据变化时执行我们的watch方法,watch选项是一个对象,键为需要观察的表达式(函数),还可以是一个对象,可以包含如下几个属性:

handler          ;对应的函数                              ;可以带两个参数,分别是新的值和旧的值,上下文为当前Vue实例
            immediate      ;侦听开始之后是否立即调用     ;默认为false
            sync           ;波尔值,是否同步执行,默认false     ;如果设置了这个属性,当数据有变化时就会立即执行了,否则放到下一个tick中排队执行

例如:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <script src="https://cdn.bootcss.com/vue/2.5.16/vue.js"></script> <title>Document</title> </head> <body> <div> <p>{{message}}</p> <button @click="test">测试</button> </div> <script> var app = new Vue({ el:'#app', data:{message:'hello world!'}, watch:{ message:function(newval,val){ console.log(newval,val) } }, methods:{ test:()=>app.message="Hello Vue!" } }) </script> </body> </html>

DOM渲染如下:

点击测试按钮后DOM变成了:

同时控制台输出:Hello Vue! hello world!

 源码分析

--------------------------------------------------------------------------------

Vue实例后会先执行_init()进行初始化(4579行)时,会执行initState()进行初始化,如下:

function initState (vm) { //第3303行 vm._watchers = []; var opts = vm.$options; if (opts.props) { initProps(vm, opts.props); } if (opts.methods) { initMethods(vm, opts.methods); } if (opts.data) { initData(vm); } else { observe(vm._data = {}, true /* asRootData */); } if (opts.computed) { initComputed(vm, opts.computed); } if (opts.watch && opts.watch !== nativeWatch) { //如果传入了watch 且 watch不等于nativeWatch(细节处理,在Firefox浏览器下Object的原型上含有一个watch函数) initWatch(vm, opts.watch); //调用initWatch()函数初始化watch } } function initWatch (vm, watch) { //第3541行 for (var key in watch) { //遍历watch里的每个元素 var handler = watch[key]; if (Array.isArray(handler)) { for (var i = 0; i < handler.length; i++) { createWatcher(vm, key, handler[i]); } } else { createWatcher(vm, key, handler); //调用createWatcher } } } function createWatcher ( //创建用户watcher vm, expOrFn, handler, options ) { if (isPlainObject(handler)) { //如果handler是个对象,则将该对象的hanler属性保存到handler里面 从这里看到值可以是个对象 options = handler; handler = handler.handler; } if (typeof handler === 'string') { handler = vm[handler]; } return vm.$watch(expOrFn, handler, options)     //最后创建一个用户watch }

Vue原型上的$watch构造函数如下:

Vue.prototype.$watch = function ( //第3596行 expOrFn,                   //监听的属性,例如例子里的message cb,                      //对应的函数 options                    //选项 ) { var vm = this; if (isPlainObject(cb)) { return createWatcher(vm, expOrFn, cb, options) } options = options || {}; options.user = true; //设置options.user为true,表示这是一个用户watch var watcher = new Watcher(vm, expOrFn, cb, options); //创建一个Watcher对象 if (options.immediate) {                    //如果有immediate选项,则直接运行 cb.call(vm, watcher.value); } return function unwatchFn () { watcher.teardown(); } }; }

侦听器对应的用户watch的user选项是true的,全局Watcher如下:

var Watcher = function Watcher ( //第3082行 vm, expOrFn, //侦听的属性:message cb, //对应的函数 options, isRenderWatcher ) { this.vm = vm; if (isRenderWatcher) { vm._watcher = this; } vm._watchers.push(this); // options if (options) { this.deep = !!options.deep; this.user = !!options.user; //用户watch这里的user属性为true this.lazy = !!options.lazy; this.sync = !!options.sync; } else { this.deep = this.user = this.lazy = this.sync = false; } this.cb = cb; this.id = ++uid$1; // uid for batching this.active = true; this.dirty = this.lazy; // for lazy watchers this.deps = []; this.newDeps = []; this.depIds = new _Set(); this.newDepIds = new _Set(); this.expression = expOrFn.toString(); // parse expression for getter if (typeof expOrFn === 'function') { this.getter = expOrFn; } else { //侦听器执行到这里, this.getter = parsePath(expOrFn); //get对应的是parsePath()返回的匿名函数 if (!this.getter) { this.getter = function () {}; "development" !== '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(); //最后会执行get()方法 }; function parsePath (path) { //解析路劲 if (bailRE.test(path)) { return } var segments = path.split('.'); return function (obj) { //返回一个函数,参数是一个对象 for (var i = 0; i < segments.length; i++) { if (!obj) { return } obj = obj[segments[i]]; } return obj } }

执行Watcher的get()方法时就将监听的元素也就是例子里的message对应的deps将当前watcher(用户watcher)作为订阅者,如下:

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

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