淺談mvvm-simple雙向綁定簡(jiǎn)單實(shí)現(xiàn)
mvvm模式解放DOM枷鎖

mvvm原理分析
JavaScript在瀏覽器中操作HTML經(jīng)歷了幾個(gè)不同階段
第一階段 直接用瀏覽器提供的原生API操作DOM元素
var dom = document.getElementById('id');
dom.innerHTML = 'hello mvvm';
第二階段 jQuery的出現(xiàn)解決了原生API的復(fù)雜性和瀏覽器間的兼容性等問題,提供了更加簡(jiǎn)易方便的API
$('#id').text('hello mvvm')
第三階段 MVC模式使前端可以和后端配合,修改服務(wù)端渲染后的頁(yè)面內(nèi)容
而隨著產(chǎn)品對(duì)于用戶體驗(yàn)的重視,交互體驗(yàn)越來越重要,僅用jQuery遠(yuǎn)遠(yuǎn)不夠。 MVVM模型解決了頻繁操作的痛點(diǎn),Model-View-ViewModel模式將數(shù)據(jù)與視圖的同步交由ViewModel完成
jQuery修改節(jié)點(diǎn)內(nèi)容:
<p>name: <span id="name">vist</span>!</p>
<p>age: <span id="age">25</span>.</p>
var name = 'bestvist';
var age = 26;
$('#name').text(name);
$('#age').text(age);
MVVM模式下只需要關(guān)注數(shù)據(jù)結(jié)構(gòu):
var me = {
name: 'vist',
age: 25
}
修改相應(yīng)屬性就好
me.name = 'bestvist'; me.age = 26;
mvvm實(shí)現(xiàn)
mvvm實(shí)現(xiàn)數(shù)據(jù)綁定的幾種方式:
- 發(fā)布-訂閱模式
- 臟值檢查
- 數(shù)據(jù)劫持
比較流行的vue采用的就是數(shù)據(jù)劫持和發(fā)布-訂閱模式,通過劫持es5提供的Object.defineProperty()中各個(gè)屬性的get,set方法, 數(shù)據(jù)更新時(shí)觸發(fā)消息給訂閱者,實(shí)現(xiàn)數(shù)據(jù)綁定功能。
Object.defineProperty(obj, prop, descriptor)方法直接在一個(gè)對(duì)象上定義一個(gè)新屬性,或者修改一個(gè)已經(jīng)存在的屬性,并返回這個(gè)對(duì)象。 該方法接受3個(gè)參數(shù):
- obj 定義屬性的對(duì)象。
- prop 被定義或修改的屬性名。
- descriptor 被定義或修改的屬性的描述符。
一般情況通過直接給對(duì)象屬性賦值來創(chuàng)建屬性或者修改對(duì)應(yīng)屬性,而使用Object.defineProperty可以修改對(duì)象屬性的一些額外默認(rèn)配置。 如:
const obj = {name: 'Tom'};
Object.defineProperty(obj, 'name', {
get: function(val) {
return 'Jerry';
}
})
console.log(obj.name);
//輸出: Jerry
Object.defineProperty詳細(xì)解釋,請(qǐng)戳這里
mvvm實(shí)現(xiàn)的主要流程:
- 數(shù)據(jù)代理,訪問實(shí)例上的屬性時(shí)直接返回對(duì)應(yīng)data里的屬性
- 數(shù)據(jù)監(jiān)聽,對(duì)實(shí)例上的屬性監(jiān)聽,如果數(shù)據(jù)改變通知訂閱者更新
- 指令解析,對(duì)每個(gè)元素節(jié)點(diǎn)進(jìn)行解析,替換數(shù)據(jù)并綁定更新函數(shù)
- 鏈接數(shù)據(jù)監(jiān)聽和指令解析,保證每個(gè)數(shù)據(jù)的更新,指令解析都可以獲取并更新視圖
實(shí)例化類:
new MVVM({
el: '#app',
data() {
return {
message: 'hello mvvm'
}
}
})
數(shù)據(jù)代理:
class MVVM {
constructor(options) {
this.$options = options || {};
let data = this._data = this.$options.data();
// 數(shù)據(jù)代理 vm.xxx => vm._data.xxx
Object.keys(data).forEach(key => {
this._proxyData(key);
});
// observe(data, this);
// this.$compile = new Compile(options.el || document.body, this);
}
_proxyData(key) {
Object.defineProperty(this, key, {
configurable: true,
enumerable: true,
get: () => {
return this._data[key];
},
set: newVal => {
this._data[key] = newVal;
}
});
}
}
數(shù)據(jù)監(jiān)聽,劫持實(shí)例屬性更新
class Observer {
constructor(data) {
this.data = data;
Object.keys(this.data).forEach(key => {
this.defineReactive(key, this.data[key]);
})
}
// 定義反應(yīng)
defineReactive(key, val) {
let dep = new Dep();
Object.defineProperty(this.data, key, {
enumerable: true,
configurable: false,
get: () => {
return val;
},
set: newVal => {
if (val === newVal) {
return;
}
val = newVal;
// 賦值對(duì)象再進(jìn)行劫持
observe(val);
... // 數(shù)據(jù)修改通知
}
})
}
}
function observe(val) {
if (!val || typeof val !== 'object') {
return;
}
return new Observer(val);
}
指令解析部分代碼
class Compile {
constructor(el, vm) {
this.$vm = vm;
this.$el = this.isElementNode(el) ? el : document.querySelector(el);
if (this.$el) {
this.$fragment = this.node2Fragment(this.$el);
this.init();
this.$el.appendChild(this.$fragment);
}
}
init() {
this.compileElement(this.$fragment);
}
node2Fragment(el) {
let fragment = document.createDocumentFragment(), child;
// 原生節(jié)點(diǎn)拷貝到fragment
while (child = el.firstChild) {
// appendChild將元素從dom上移到fragment
fragment.appendChild(child);
}
return fragment;
}
compileElement(el) {
let childNodes = el.childNodes;
[].slice.call(childNodes).forEach(node => {
let text = node.textContent;
let reg = /\{\{(.*)\}\}/;
if (this.isElementNode(node)) {
this.compile(node);
} else if (this.isTextNode(node) && reg.test(text)) {
this.compileText(node, RegExp.$1);
}
if (node.childNodes && node.childNodes.length) {
this.compileElement(node);
}
})
}
}
其中
while (child = el.firstChild) {
// appendChild將元素從dom上移到fragment
fragment.appendChild(child);
}
通過appendChild改變?cè)璬om結(jié)構(gòu)特點(diǎn),逐步把dom元素節(jié)點(diǎn)移到fragment中。
總結(jié)
以數(shù)據(jù)流為導(dǎo)向的mvvm模式極大的簡(jiǎn)化前端對(duì)于dom的操作,加快前端開發(fā)速度,同時(shí)也提高了用戶體驗(yàn)。
參考:
剖析Vue原理&實(shí)現(xiàn)雙向綁定MVVM mvvm廖雪峰
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Vue3 + CSS實(shí)現(xiàn)一個(gè)噴火龍動(dòng)畫效果
不知不覺中,2023年已然逝去了,龍年到了,所以本文小編使用Vue3 + CSS實(shí)現(xiàn)一個(gè)噴火龍的動(dòng)畫效果,文中有相關(guān)的代碼示例供大家參考,具有一定的參考價(jià)值,感興趣的同學(xué)可以自己動(dòng)手嘗試一下2024-02-02
vue組件props不同數(shù)據(jù)類型傳參的默認(rèn)值問題
這篇文章主要介紹了vue組件props不同數(shù)據(jù)類型傳參的默認(rèn)值問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-07-07
AntV+Vue實(shí)現(xiàn)導(dǎo)出圖片功能
AntV?組織圖操作完畢以后,需要點(diǎn)擊按鈕將畫布以圖片的形式導(dǎo)出,這篇文章主要介紹了AntV結(jié)合Vue實(shí)現(xiàn)導(dǎo)出圖片功能,需要的朋友可以參考下2023-01-01
解決VueCil代理本地proxytable無效報(bào)錯(cuò)404的問題
這篇文章主要介紹了解決VueCil代理本地proxytable無效報(bào)錯(cuò)404的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-11-11
Vue插件實(shí)現(xiàn)過程中遇到的問題總結(jié)
隨著Vue.js越來越火,Vue.js 的相關(guān)插件也在不斷的被貢獻(xiàn)出來,數(shù)不勝數(shù),這篇文章主要給大家介紹了關(guān)于Vue插件實(shí)現(xiàn)過程中遇到的問題,需要的朋友可以參考下2021-08-08
前端vue如何根據(jù)菜單自動(dòng)生成路由(動(dòng)態(tài)配置前端路由)
估計(jì)有不少人遇過這樣的需求:根據(jù)后臺(tái)數(shù)據(jù)動(dòng)態(tài)添加路由和菜單,這篇文章主要給大家介紹了關(guān)于前端vue如何根據(jù)菜單自動(dòng)生成路由的相關(guān)資料,需要的朋友可以參考下2024-04-04

