溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Vue 2.0 偵聽(tīng)器 watch屬性代碼詳解

發(fā)布時(shí)間:2020-10-20 19:37:00 來(lái)源:腳本之家 閱讀:148 作者:大沙漠 欄目:web開發(fā)

用法

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

先來(lái)看看官網(wǎng)的介紹:

官網(wǎng)介紹的很好理解了,也就是監(jiān)聽(tīng)一個(gè)數(shù)據(jù)的變化,當(dāng)該數(shù)據(jù)變化時(shí)執(zhí)行我們的watch方法,watch選項(xiàng)是一個(gè)對(duì)象,鍵為需要觀察的表達(dá)式(函數(shù)),還可以是一個(gè)對(duì)象,可以包含如下幾個(gè)屬性:

            handler          ;對(duì)應(yīng)的函數(shù)                              ;可以帶兩個(gè)參數(shù),分別是新的值和舊的值,上下文為當(dāng)前Vue實(shí)例
            immediate      ;偵聽(tīng)開始之后是否立即調(diào)用     ;默認(rèn)為false
            sync           ;波爾值,是否同步執(zhí)行,默認(rèn)false     ;如果設(shè)置了這個(gè)屬性,當(dāng)數(shù)據(jù)有變化時(shí)就會(huì)立即執(zhí)行了,否則放到下一個(gè)tick中排隊(duì)執(zhí)行

例如:

<!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">測(cè)試</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渲染如下:

Vue 2.0 偵聽(tīng)器 watch屬性代碼詳解

點(diǎn)擊測(cè)試按鈕后DOM變成了:

Vue 2.0 偵聽(tīng)器 watch屬性代碼詳解

同時(shí)控制臺(tái)輸出:Hello Vue! hello world!

 源碼分析

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

  Vue實(shí)例后會(huì)先執(zhí)行_init()進(jìn)行初始化(4579行)時(shí),會(huì)執(zhí)行initState()進(jìn)行初始化,如下:

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(細(xì)節(jié)處理,在Firefox瀏覽器下Object的原型上含有一個(gè)watch函數(shù))
  initWatch(vm, opts.watch);                 //調(diào)用initWatch()函數(shù)初始化watch
 }
}

function initWatch (vm, watch) {  //第3541行
 for (var key in watch) {            //遍歷watch里的每個(gè)元素
  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);        //調(diào)用createWatcher
  }
 }
}

function createWatcher (             //創(chuàng)建用戶watcher
 vm,
 expOrFn,
 handler,
 options
) {
 if (isPlainObject(handler)) {           //如果handler是個(gè)對(duì)象,則將該對(duì)象的hanler屬性保存到handler里面 從這里看到值可以是個(gè)對(duì)象
  options = handler;
  handler = handler.handler;          
 }
 if (typeof handler === 'string') {        
  handler = vm[handler];
 }
 return vm.$watch(expOrFn, handler, options)     //最后創(chuàng)建一個(gè)用戶watch
}

Vue原型上的$watch構(gòu)造函數(shù)如下:

Vue.prototype.$watch = function (   //第3596行
  expOrFn,                   //監(jiān)聽(tīng)的屬性,例如例子里的message
  cb,                      //對(duì)應(yīng)的函數(shù)
  options                    //選項(xiàng)
 ) {
  var vm = this;
  if (isPlainObject(cb)) {
   return createWatcher(vm, expOrFn, cb, options)
  }
  options = options || {};
  options.user = true;                   //設(shè)置options.user為true,表示這是一個(gè)用戶watch
  var watcher = new Watcher(vm, expOrFn, cb, options);   //創(chuàng)建一個(gè)Watcher對(duì)象
  if (options.immediate) {                    //如果有immediate選項(xiàng),則直接運(yùn)行
   cb.call(vm, watcher.value);
  }
  return function unwatchFn () {
   watcher.teardown();
  }
 };
}

偵聽(tīng)器對(duì)應(yīng)的用戶watch的user選項(xiàng)是true的,全局Watcher如下:

var Watcher = function Watcher ( //第3082行
 vm,
 expOrFn,               //偵聽(tīng)的屬性:message
 cb,                  //對(duì)應(yīng)的函數(shù)
 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 {                         //偵聽(tīng)器執(zhí)行到這里,
  this.getter = parsePath(expOrFn);            //get對(duì)應(yīng)的是parsePath()返回的匿名函數(shù)
  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();                      //最后會(huì)執(zhí)行g(shù)et()方法
}; 
function parsePath (path) {       //解析路勁
 if (bailRE.test(path)) { 
  return
 }
 var segments = path.split('.');
 return function (obj) {        //返回一個(gè)函數(shù),參數(shù)是一個(gè)對(duì)象
  for (var i = 0; i < segments.length; i++) {
   if (!obj) { return }
   obj = obj[segments[i]];
  }
  return obj
 }
}

執(zhí)行Watcher的get()方法時(shí)就將監(jiān)聽(tīng)的元素也就是例子里的message對(duì)應(yīng)的deps將當(dāng)前watcher(用戶watcher)作為訂閱者,如下:

Watcher.prototype.get = function get () {   //第3135行
 pushTarget(this);                 //將當(dāng)前用戶watch保存到Dep.target總=中
 var value;
 var vm = this.vm;
 try {
  value = this.getter.call(vm, vm);        //執(zhí)行用戶wathcer的getter()方法,此方法會(huì)將當(dāng)前用戶watcher作為訂閱者訂閱起來(lái)
 } 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();                  //恢復(fù)之前的watcher
  this.cleanupDeps();
 }
 return value
};

當(dāng)我們點(diǎn)擊按鈕了修改了app.message時(shí)就會(huì)執(zhí)行app.message對(duì)應(yīng)的訪問(wèn)控制器的set()方法,就會(huì)執(zhí)行這個(gè)用戶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,則直接運(yùn)行this.run獲取結(jié)果
  this.run();                   
 } else {
  queueWatcher(this);               //否則調(diào)用queueWatcher()函數(shù)把所有要執(zhí)行update()的watch push到隊(duì)列中
 }
};

Watcher.prototype.run = function run () {   //第3215行 執(zhí)行,會(huì)調(diào)用get()獲取對(duì)應(yīng)的值 
 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) {            //如果是個(gè)用戶 watcher
    try {
     this.cb.call(this.vm, value, oldValue);    //執(zhí)行這個(gè)回調(diào)函數(shù) vm作為上下文 參數(shù)1為新值 參數(shù)2為舊值     也就是最后我們自己定義的function(newval,val){ console.log(newval,val) }函數(shù)
    } catch (e) { 
     handleError(e, this.vm, ("callback for watcher \"" + (this.expression) + "\""));
    }
   } else {
    this.cb.call(this.vm, value, oldValue);
   }
  }
 }
};

對(duì)于偵聽(tīng)器來(lái)說(shuō),Vue內(nèi)部的流程就是這樣子

總結(jié)

以上所述是小編給大家介紹的Vue 2.0 偵聽(tīng)器 watch屬性代碼詳解,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)億速云網(wǎng)站的支持!
如果你覺(jué)得本文對(duì)你有幫助,歡迎轉(zhuǎn)載,煩請(qǐng)注明出處,謝謝!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI