Vue雙向綁定原理(源碼深入解析)

  • 訂閱/發(fā)布模式(subscribe&publish)

訂閱發(fā)布模式(又稱觀察者模式)定義了一種一對多的關(guān)系,
讓多個觀察者同時監(jiān)聽某一個主題對象,這個主題對象的狀態(tài)發(fā)生改變時就會通知所有觀察者對象。

發(fā)布者發(fā)出通知 => 主題對象收到通知并推送給訂閱者 => 訂閱者執(zhí)行相應操作

Vue的配置

<template>
 <div>
<input v-model="a" type="text"/>
{{a}}
<div>
</template>
new Vue({
data: {
a: 1
},
computed: {
b: function() {
return this.a + 1;
}
}
})
// 發(fā)布者
var pub = {
    publish: function() {
        dep.notify()
    }
}
// 訂閱者1,2
var sub1 = { update: function(val) {
// 更新DOM1上的數(shù)據(jù)
 }
var sub2 = { update: function(val) {
// 更新DOM2上的數(shù)據(jù)
 }
// 主題對象,比如data對象的屬性a
function Dep() {
    this.subs = [sub1, sub2];
}
// a屬性值變化之后,使用它的所有地方都要發(fā)生變化,比如computed的b就是以是一個訂閱者,和模板里的a
Dep.prorotype.notify = function() {
  this.subs.forEach((sub) => {
    sub.update();
})
// 往主題對象,添加新的訂閱者
Dep.prorotype.addSub= function() {
  this.subs.push(sub);
}

Vue的源碼解析可以分為3步驟

  1. 輸入框以及文本節(jié)點與 data 中的數(shù)據(jù)綁定
    將模板與data進行替換,最后輸出可以渲染有真實數(shù)據(jù)的Dom(即渲染函數(shù))
  2. 輸入框內(nèi)容變化時,data 中的數(shù)據(jù)同步變化。即 view => model 的變化。
  3. data 中的數(shù)據(jù)變化時,文本節(jié)點的內(nèi)容同步變化。即 model => view 的變化。
DocumentFragment
  • DocumentFragment(文檔片段)可以看作節(jié)點容器,它可以包含多個子節(jié)點,當我們將它插入到 DOM 中時,只有它的子節(jié)點會插入目標節(jié)點,所以把它看作一組節(jié)點的容器。使用 DocumentFragment 處理節(jié)點,速度和性能遠遠優(yōu)于直接操作 DOM。

  • Vue 進行編譯時,就是將掛載目標的所有子節(jié)點劫持(真的是劫持,通過 append 方法,DOM 中的節(jié)點會被自動刪除)到 DocumentFragment 中,經(jīng)過一番處理后,再將 DocumentFragment 整體返回插入掛載目標。

1. 輸入框以及文本節(jié)點與 data 中的數(shù)據(jù)綁定,將模板與data進行替換,最后輸出可以渲染有真實數(shù)據(jù)的Dom(即渲染函數(shù))
function Compile(el) {
    if (this.$el) {
    // 將掛載元素里的字節(jié)點拷貝到fragment
        this.$fragment = this.node2Fragment(this.$el);
    // 執(zhí)行編譯函數(shù),將模板轉(zhuǎn)成DOM
        this.init();
      // 將替換好真實數(shù)據(jù)的Dom插入到掛載的元素里
        this.$el.appendChild(this.$fragment);
    }
}
Compile.prototype = {
    // 初始化,執(zhí)行編譯函數(shù)
    init: function() { this.compileElement(this.$fragment); },
    //// 將掛載元素里的字節(jié)點拷貝到fragment
    node2Fragment: function(el) {
        var fragment = document.createDocumentFragment(), child;
        // 將原生節(jié)點拷貝到fragment
        while (child = el.firstChild) {
            fragment.appendChild(child);
        }
        return fragment;
    }
    //編譯函數(shù),
    compileElement: function(el) {
        var childNodes = el.childNodes, me = this;
        [].slice.call(childNodes).forEach(function(node) {
            var text = node.textContent;
            var reg = /\{\{(.*)\}\}/;    // 表達式文本
            // 按元素節(jié)點方式編譯
            if (me.isElementNode(node)) {
                me.compile(node);
                // 按{{}}字符串模板的文本節(jié)點方式編譯
            } else if (me.isTextNode(node) && reg.test(text)) {
                me.compileText(node, RegExp.$1);
            }
            // 遍歷子節(jié)點,再進行編譯
            if (node.childNodes && node.childNodes.length) {
                me.compileElement(node);
            }
        });
    }
}
2. 輸入框內(nèi)容變化時,data 中的數(shù)據(jù)同步變化。即 view => model 的變化。
3. 發(fā)出通知 dep.notify() => 觸發(fā)訂閱者的 update 方法 => 更新視圖。
function Compile(el) {
        var childNodes = el.childNodes, me = this;
        [].slice.call(childNodes).forEach(function(node) {
            var text = node.textContent;
            var reg = /\{\{(.*)\}\}/;    // 表達式文本
            // 按元素節(jié)點方式監(jiān)聽數(shù)據(jù)
            if (me.isElementNode(node)) {
                new Watcher(this, node, cb)
                // 按{{}}字符串模板的文本節(jié)點方式監(jiān)聽數(shù)據(jù)
            } else if (me.isTextNode(node) && reg.test(text)) {
                new Watcher(this, node, cb)
            }
            // 遍歷子節(jié)點,監(jiān)聽數(shù)據(jù)
            if (node.childNodes && node.childNodes.length) {
                new Watcher(this, childNodes , cb)
            }
        });
}
// 對DocumentFragment里的元素的data對象的屬性值進行監(jiān)聽
function Watcher(vm, exp, cb) {
    this.cb = cb;
    this.vm = vm;
    this.exp = exp;
    // 此處為了觸發(fā)屬性的getter,從而在dep添加自己,結(jié)合Observer更易理解
    this.value = this.get(); 
}
Watcher.prototype = {
    update: function() {
        this.run();    // 屬性值變化收到通知
    },
    run: function() {
        var value = this.get(); // 取到最新值
        var oldVal = this.value;
        if (value !== oldVal) {
            this.value = value;
            this.cb.call(this.vm, value, oldVal); // 執(zhí)行Compile中綁定的回調(diào),更新視圖
        }
    },
    get: function() {
        Dep.target = this;    // 將當前訂閱者指向自己
        var value = this.vm[exp];    // 觸發(fā)getter,添加自己到屬性訂閱器中
        Dep.target = null;    // 添加完畢,重置
        return value;
    }
};
// 這里再次列出Observer和Dep,方便理解
Object.defineProperty(data, key, {
    get: function() {
        // 由于需要在閉包內(nèi)添加watcher,所以可以在Dep定義一個全局target屬性,暫存watcher, 添加完移除
        Dep.target && dep.addDep(Dep.target);
        return val;
    }
    // ... 省略
});
Dep.prototype = {
    notify: function() {
        this.subs.forEach(function(sub) {
            sub.update(); // 調(diào)用訂閱者的update方法,通知變化
        });
    }
};

文章參考:
剖析Vue原理實現(xiàn)雙向綁定MVVM
Vue.js雙向綁定的實現(xiàn)原理

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容