用法css
先來看看官網的介紹:html
官網介紹的很好理解了,也就是監聽一個數據的變化,當該數據變化時執行咱們的watch方法,watch選項是一個對象,鍵爲須要觀察的數據名,值爲一個表達式(函數),還能夠是一個對象,若是時對象能夠包含以下幾個屬性:vue
handler ;對應的函數 ;能夠帶兩個參數,分別是新的值和舊的值,上下文爲當前Vue實例
immediate ;偵聽開始以後是否當即調用 ;默認爲false
sync ;波爾值,是否同步執行,默認false ;若是設置了這個屬性,當數據有變化時就會當即執行了,不然放到下一個tick中排隊執行express
例如:瀏覽器
<!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 id="app"> <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渲染以下:app
點擊測試按鈕後DOM變成了:函數
同時控制檯輸出:Hello Vue! hello world!源碼分析
源碼分析測試
Vue實例後會先執行_init()進行初始化(4579行)時,會執行initState()進行初始化,以下:ui
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裏面 ;這裏對應watch的值爲對象的狀況 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選項,則直接運行 ;這裏對應watch的值爲對象且含有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)做爲訂閱者,以下:
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獲取結果 ;這裏對應watch的值爲對象且含有sync屬性的狀況 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內部的流程就是這樣子