溫馨提示×

溫馨提示×

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

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

VueJS中數(shù)據(jù)驅(qū)動和依賴追蹤的示例分析

發(fā)布時間:2021-07-22 15:59:17 來源:億速云 閱讀:183 作者:小新 欄目:web開發(fā)

這篇文章主要介紹了VueJS中數(shù)據(jù)驅(qū)動和依賴追蹤的示例分析,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。

在之前實(shí)現(xiàn)一個自己的Mvvm中,用 setter 來觀測model,將界面上所有的 viewModel 綁定到 model 上。 當(dāng)model改變,更新所有的viewModel,將新值渲染到界面上 。同時監(jiān)聽界面上通過v-model 綁定的所有 input,并通過 addEventListener事件將新值更新到 model 上,以此來完成雙向綁定 。

但是那段程序除了用來理解 defineProperty,其它一文不值。

  1. 沒有編譯節(jié)點(diǎn) 。

  2. 沒有處理表達(dá)式依賴 。

這里我將解決表達(dá)式依賴這個問題,vue 模板的編譯我會在下一節(jié)介紹 。

為數(shù)據(jù)定義 getter & setter

class Observer {
  constructor(data) {
    this._data = data;
    this.walk(this._data);
  }

  walk(data) {
    Object.keys(data).forEach((key) => { this.defineRective(data, key, data[key]) })
  };
  defineRective(vm, key, value) {
    var self = this;
    if (value && typeof value === "object") {
      this.walk(value);
    }
    Object.defineProperty(vm, key, {
      get: function() {
        return value;
      },
      set: function(newVal) {
        if (value != newVal) {
          if (newVal && typeof newVal === "object") {
            self.walk(newVal);
          }
          value = newVal;
        }
      }
    })
  }
}

module.exports = Observer;

這樣,就為每個屬性添加了 getter 和 setter ,當(dāng)屬性是一個對象,那么就遞歸添加。

一旦獲取屬性值或者為屬性賦值就會觸發(fā) get 或 set ,當(dāng)觸發(fā)了 set,即model變化,就可以發(fā)布一個消息,通知所有viewModel 更新。

defineRective(vm, key, value) {
  // 將這個屬性的依賴表達(dá)式存儲在閉包中。
  var dep = new Dep();
  var self = this;
  if (value && typeof value === "object") {
    this.walk(value);
  }
  Object.defineProperty(vm, key, {
    get: function() {
      return value;
    },
    set: function(newVal) {
      if (value != newVal) {
        if (newVal && typeof newVal === "object") {
          self.walk(newVal);
        }
        value = newVal;
        // 通知所有的 viewModel 更新
        dep.notify();
      }
    }
  })
}

那么怎么定義 Dep 呢??

class Dep {
  constructor() {
    // 依賴列表
    this.dependences = [];
  }
  // 添加依賴
  addDep(watcher) {
    if (watcher) {
      this.dependences.push(watcher);
    }
  }
  // 通知所有依賴更新
  notify() {
    this.dependences.forEach((watcher) => {
      watcher.update();
    })
  }
}

module.exports = Dep;

這里的每個依賴就是一個Watcher 。

看看如何定義 Watcher

這里每一個 Watcher 都會有一個唯一的id號,它擁有一個表達(dá)式和一個回調(diào)函數(shù) 。

比如 表達(dá)式 a +b ; 會在get 計算時 訪問 a 與 b , 由于 JavaScript是單線程,任一時刻只有一處JavaScript代碼在執(zhí)行, 用Dep.target 作為一個全局變量來表示當(dāng)前 Watcher 的表達(dá)式,然后通過 compute 訪問 a ,b ,觸發(fā) a 與b 的getter,在 getter 里面將 Dep.target 添加為依賴 。

一旦 a 與 b 的set 觸發(fā),調(diào)用 update 函數(shù),更新依賴的值 。

var uid = 0;
class Watcher {
  constructor(viewModel, exp, callback) {
    this.viewModel = viewModel;
    this.id = uid++;
    this.exp = exp;
    this.callback = callback;
    this.oldValue = "";
    this.update();
  }

  get() {
    Dep.target = this;
    var res = this.compute(this.viewModel, this.exp);
    Dep.target = null;
    return res;
  }

  update() {
    var newValue = this.get();
    if (this.oldValue === newValue) {
      return;
    }
    // callback 里進(jìn)行Dom 的更新操作
    this.callback(newValue, this.oldValue);
    this.oldValue = newValue;
  }

  compute(viewModel, exp) {
    var res = replaceWith(viewModel, exp);
    return res;
  }
}

module.exports = Watcher;

由于當(dāng)前表達(dá)式需要在 當(dāng)前的model下面執(zhí)行,所以 采用replaceWith 函數(shù)來代替 with ,具體可以查看另一篇隨筆javascript 中 with 的替代語法。

通過get 添加依賴

Object.defineProperty(vm, key, {
  get: function() {
    var watcher = Dep.target;
    if (watcher && !dep.dependences[watcher.id]) {
      dep.addDep(watcher);
    }
    return value;
  },
  set: function(newVal) {
    if (value != newVal) {
      if (newVal && typeof newVal === "object") {
        self.walk(newVal);
      }
      value = newVal;
      dep.notify();
    }
  }
})

這種添加依賴的方式實(shí)在太巧妙了 。

 這里我畫了一個圖來描述

VueJS中數(shù)據(jù)驅(qū)動和依賴追蹤的示例分析

最后通過一段代碼簡單測試一下

const Observer = require('./Observer.js');
const Watcher = require('./watcher.js');
var data = {
  a: 10,
  b: {
    c: 5,
    d: {
      e: 20,
    }
  }
}

var observe = new Observer(data);

var watcher = new Watcher(data, "a+b.c", function(newValue, oldValue) {
  console.log("new value is " + newValue);
  console.log("oldValue is " + oldValue);
});
console.log("\r\n");
console.log("a has changed to 50,then the expr should has value 55");
data.a = 50;

console.log("\r\n");
console.log("b.c has changed to 50,then the expr should has value 122");
data.b.c = 72;;

console.log("\r\n");
console.log("b.c has reseted an object,then the expr should has value 80");
data.b = { c: 30 }

VueJS中數(shù)據(jù)驅(qū)動和依賴追蹤的示例分析

感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“VueJS中數(shù)據(jù)驅(qū)動和依賴追蹤的示例分析”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識等著你來學(xué)習(xí)!

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

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

vue
AI