Vue2.x 的雙向綁定原理及實(shí)現(xiàn)
作者:九旬
來源:SegmentFault 思否社區(qū)
Vue 數(shù)據(jù)雙向綁定原理
Vue 是利用的 Object.defineProperty() 方法進(jìn)行的數(shù)據(jù)劫持,利用 set、get 來檢測(cè)數(shù)據(jù)的讀寫。
https://jsrun.net/RMIKp/embedded/all/light
MVVM 框架主要包含兩個(gè)方面,數(shù)據(jù)變化更新視圖,視圖變化更新數(shù)據(jù)。
視圖變化更新數(shù)據(jù),如果是像 input 這種標(biāo)簽,可以使用 oninput 事件..
數(shù)據(jù)變化更新視圖可以使用 Object.definProperty() 的 set 方法可以檢測(cè)數(shù)據(jù)變化,當(dāng)數(shù)據(jù)改變就會(huì)觸發(fā)這個(gè)函數(shù),然后更新視圖。
實(shí)現(xiàn)過程
我們知道了如何實(shí)現(xiàn)雙向綁定了,首先要對(duì)數(shù)據(jù)進(jìn)行劫持監(jiān)聽,所以我們需要設(shè)置一個(gè) Observer 函數(shù),用來監(jiān)聽所有屬性的變化。
如果屬性發(fā)生了變化,那就要告訴訂閱者 watcher 看是否需要更新數(shù)據(jù),如果訂閱者有多個(gè),則需要一個(gè) Dep 來收集這些訂閱者,然后在監(jiān)聽器 observer 和 watcher 之間進(jìn)行統(tǒng)一管理。
還需要一個(gè)指令解析器 compile,對(duì)需要監(jiān)聽的節(jié)點(diǎn)和屬性進(jìn)行掃描和解析。
因此,流程大概是這樣的:
實(shí)現(xiàn)一個(gè)監(jiān)聽器 Observer,用來劫持并監(jiān)聽所有屬性,如果發(fā)生變動(dòng),則通知訂閱者。 實(shí)現(xiàn)一個(gè)訂閱者 Watcher,當(dāng)接到屬性變化的通知時(shí),執(zhí)行對(duì)應(yīng)的函數(shù),然后更新視圖,使用 Dep 來收集這些 Watcher。 實(shí)現(xiàn)一個(gè)解析器 Compile,用于掃描和解析的節(jié)點(diǎn)的相關(guān)指令,并根據(jù)初始化模板以及初始化相應(yīng)的訂閱器。

顯示一個(gè) Observer
Object.defineProperty() 通過遞歸的方式對(duì)所有屬性都添加 setter、getter 方法進(jìn)行監(jiān)聽。var library = {
book1: {
name: "",
},
book2: "",
};
observe(library);
library.book1.name = "vue權(quán)威指南"; // 屬性name已經(jīng)被監(jiān)聽了,現(xiàn)在值為:“vue權(quán)威指南”
library.book2 = "沒有此書籍"; // 屬性book2已經(jīng)被監(jiān)聽了,現(xiàn)在值為:“沒有此書籍”
// 為數(shù)據(jù)添加檢測(cè)
function defineReactive(data, key, val) {
observe(val); // 遞歸遍歷所有子屬性
let dep = new Dep(); // 新建一個(gè)dep
Object.defineProperty(data, key, {
enumerable: true,
configurable: true,
get: function() {
if (Dep.target) {
// 判斷是否需要添加訂閱者,僅第一次需要添加,之后就不用了,詳細(xì)看Watcher函數(shù)
dep.addSub(Dep.target); // 添加一個(gè)訂閱者
}
return val;
},
set: function(newVal) {
if (val == newVal) return; // 如果值未發(fā)生改變就return
val = newVal;
console.log(
"屬性" + key + "已經(jīng)被監(jiān)聽了,現(xiàn)在值為:“" + newVal.toString() + "”"
);
dep.notify(); // 如果數(shù)據(jù)發(fā)生變化,就通知所有的訂閱者。
},
});
}
// 監(jiān)聽對(duì)象的所有屬性
function observe(data) {
if (!data || typeof data !== "object") {
return; // 如果不是對(duì)象就return
}
Object.keys(data).forEach(function(key) {
defineReactive(data, key, data[key]);
});
}
// Dep 負(fù)責(zé)收集訂閱者,當(dāng)屬性發(fā)生變化時(shí),觸發(fā)更新函數(shù)。
function Dep() {
this.subs = {};
}
Dep.prototype = {
addSub: function(sub) {
this.subs.push(sub);
},
notify: function() {
this.subs.forEach((sub) => sub.update());
},
};
實(shí)現(xiàn) Watcher
function Watcher(vm, exp, cb) {
this.cb = cb;
this.vm = vm;
this.exp = exp;
this.value = this.get(); // 將自己添加到訂閱器的操作
}
Watcher.prototype = {
update: function() {
this.run();
},
run: function() {
var value = this.vm.data[this.exp];
var oldVal = this.value;
if (value !== oldVal) {
this.value = value;
this.cb.call(this.vm, value, oldVal);
}
},
get: function() {
Dep.target = this; // 緩存自己,用于判斷是否添加watcher。
var value = this.vm.data[this.exp]; // 強(qiáng)制執(zhí)行監(jiān)聽器里的get函數(shù)
Dep.target = null; // 釋放自己
return value;
},
};
// MyVue
proxyKeys(key) {
var self = this;
Object.defineProperty(this, key, {
enumerable: false,
configurable: true,
get: function proxyGetter() {
return self.data[key];
},
set: function proxySetter(newVal) {
self.data[key] = newVal;
}
});
}
實(shí)現(xiàn) Compile
解析模板指令,并替換模板數(shù)據(jù),初始化視圖。 將模板指定對(duì)應(yīng)的節(jié)點(diǎn)綁定對(duì)應(yīng)的更新函數(shù),初始化相應(yīng)的訂閱器。
function nodeToFragment(el) {
var fragment = document.createDocumentFragment();
var child = el.firstChild;
while (child) {
// 將Dom元素移入fragment中
fragment.appendChild(child);
child = el.firstChild;
}
return fragment;
}
function compileElement (el) {
var childNodes = el.childNodes;
var self = this;
[].slice.call(childNodes).forEach(function(node) {
var reg = /\{\{(.*)\}\}/; // 匹配{{xx}}
var text = node.textContent;
if (self.isTextNode(node) && reg.test(text)) { // 判斷是否是符合這種形式{{}}的指令
self.compileText(node, reg.exec(text)[1]);
}
if (node.childNodes && node.childNodes.length) {
self.compileElement(node); // 繼續(xù)遞歸遍歷子節(jié)點(diǎn)
}
});
},
function compileText (node, exp) {
var self = this;
var initText = this.vm[exp];
updateText(node, initText); // 將初始化的數(shù)據(jù)初始化到視圖中
new Watcher(this.vm, exp, function (value) { // 生成訂閱器并綁定更新函數(shù)
self.updateText(node, value);
});
},
function updateText (node, value) {
node.textContent = typeof value == 'undefined' ? '' : value;
}
function compile(node) {
var nodeAttrs = node.attributes;
var self = this;
Array.prototype.forEach.call(nodeAttrs, function(attr) {
var attrName = attr.name;
if (isDirective(attrName)) {
var exp = attr.value;
var dir = attrName.substring(2);
if (isEventDirective(dir)) {
// 事件指令
self.compileEvent(node, self.vm, exp, dir);
} else {
// v-model 指令
self.compileModel(node, self.vm, exp, dir);
}
node.removeAttribute(attrName); // 解析完畢,移除屬性
}
});
}
// v-指令解析
function isDirective(attr) {
return attr.indexOf("v-") == 0;
}
// on: 指令解析
function isEventDirective(dir) {
return dir.indexOf("on:") === 0;
}
完整版 myVue
class MyVue {
constructor(options) {
var self = this;
this.data = options.data;
this.methods = options.methods;
Object.keys(this.data).forEach(function(key) {
self.proxyKeys(key);
});
observe(this.data);
new Compile(options.el, this);
options.mounted.call(this); // 所有事情處理好后執(zhí)行mounted函數(shù)
}
proxyKeys(key) {
// 將this.data屬性代理到this上
var self = this;
Object.defineProperty(this, key, {
enumerable: false,
configurable: true,
get: function getter() {
return self.data[key];
},
set: function setter(newVal) {
self.data[key] = newVal;
},
});
}
}
https://ustbhuangyi.github.io/vue-analysis/v2/reactive/
https://juejin.cn/book/6844733705089449991/section/6844733705227862023
https://www.cnblogs.com/canfoo/p/6891868.html

評(píng)論
圖片
表情
