Vue 2.0 偵聽器 watch屬性代碼詳解

這篇文章主要介紹了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 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渲染如下:

點擊測試按鈕後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)作爲訂閱者,如下:

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屬性代碼詳解,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回覆大家的。在此也非常感謝大家對神馬文庫網站的支持!
如果你覺得本文對你有幫助,歡迎轉載,煩請註明出處,謝謝!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章