vue實現(xiàn)簡單的MVVM框架
不知不覺接觸前端的時間已經(jīng)過去半年了,越來越發(fā)覺對知識的學(xué)習(xí)不應(yīng)該只停留在會用的層面,這在我學(xué)jQuery的一段時間后便有這樣的體會。
雖然jQuery只是一個JS的代碼庫,只要會一些JS的基本操作學(xué)習(xí)一兩天就能很快掌握jQuery的基本語法并熟練使用,但是如果不了解jQUery庫背后的實現(xiàn)原理,相信只要你一段時間不再使用jQuery的話就會把jQuery忘得一干二凈,這也許就是知其然不知其所以然的后果。
最近在學(xué)vue的時候又再一次經(jīng)歷了這樣的困惑,雖然能夠比較熟練的掌握vue的基本使用,也能夠?qū)V*模式、數(shù)據(jù)劫持、雙向數(shù)據(jù)綁定、數(shù)據(jù)代理侃上兩句。但是要是稍微深入一點就有點吃力了。所以這幾天痛下決心研究大量技術(shù)文章(起初嘗試看早期源碼,無奈vue與jQuery不是一個層級的,相比于jQuery,vue是真正意義上的前端框架。只能無奈棄坑轉(zhuǎn)而看技術(shù)博客),對vue也算有了一個管中窺豹的認(rèn)識。最后嘗試實踐一下自己學(xué)到的知識,基于數(shù)據(jù)代理、數(shù)據(jù)劫持、模板解析、雙向綁定實現(xiàn)了一個小型的vue框架。
溫馨提示:文章是按照每個模塊的實現(xiàn)依賴關(guān)系來進(jìn)行分析的,但是在閱讀的時候可以按照vue的執(zhí)行順序來分析,這樣對初學(xué)者更加的友好。推薦的閱讀順序為:實現(xiàn)VMVM、數(shù)據(jù)代理、實現(xiàn)Observe、實現(xiàn)Complie、實現(xiàn)Watcher。
源碼:https://github.com/yuliangbin/MVVM
功能演示如下所示:

數(shù)據(jù)代理
以下面這個模板為例,要替換的根元素“#mvvm-app”內(nèi)只有一個文本節(jié)點#text,#text的內(nèi)容為{{name}}。我們就以下面這個模板詳細(xì)了解一下VUE框架的大體實現(xiàn)流程。
<body>
<div id="mvvm-app">
{{name}}
</div>
<script src="./js/observer.js"></script>
<script src="./js/watcher.js"></script>
<script src="./js/compile.js"></script>
<script src="./js/mvvm.js"></script>
<script>
let vm = new MVVM({
el: "#mvvm-app",
data: {
name: "hello world"
},
})
</script>
</body>
數(shù)據(jù)代理
1、什么是數(shù)據(jù)代理
在vue里面,我們將數(shù)據(jù)寫在data對象中。但是我們在訪問data里的數(shù)據(jù)時,既可以通過vm.data.name訪問,也可以通過vm.name訪問。這就是數(shù)據(jù)代理:在一個對象中,可以動態(tài)的訪問和設(shè)置另一個對象的屬性。
2、實現(xiàn)原理
我們知道靜態(tài)綁定(如vm.name = vm.data.name)可以一次性的將結(jié)果賦給變量,而使用Object.defineProperty()方法來綁定則可以通過set和get函數(shù)實現(xiàn)賦值的中間過程,從而實現(xiàn)數(shù)據(jù)的動態(tài)綁定。具體實現(xiàn)如下:
let obj = {};
let obj1 = {
name: 'xiaoyu',
age: 18,
}
//實現(xiàn)origin對象代理target對象
function proxyData(origin,target){
Object.keys(target).forEach(function(key){
Object.defineProperty(origin,key,{//定義origin對象的key屬性
enumerable: false,
configurable: true,
get: function getter(){
return target[key];//origin[key] = target[key];
},
set: function setter(newValue){
target[key] = newValue;
}
})
})
}
vue中的數(shù)據(jù)代理也是通過這種方式來實現(xiàn)的。
function MVVM(options) {
this.$options = options || {};
var data = this._data = this.$options.data;
var _this = this;//當(dāng)前實例vm
// 數(shù)據(jù)代理
// 實現(xiàn) vm._data.xxx -> vm.xxx
Object.keys(data).forEach(function(key) {
_this._proxyData(key);
});
observe(data, this);
this.$compile = new Compile(options.el || document.body, this);
}
MVVM.prototype = {
_proxyData: function(key) {
var _this = this;
if (typeof key == 'object' && !(key instanceof Array)){//這里只實現(xiàn)了對對象的監(jiān)聽,沒有實現(xiàn)數(shù)組的
this._proxyData(key);
}
Object.defineProperty(_this, key, {
configurable: false,
enumerable: true,
get: function proxyGetter() {
return _this._data[key];
},
set: function proxySetter(newVal) {
_this._data[key] = newVal;
}
});
},
};
實現(xiàn)Observe
1、雙向數(shù)據(jù)綁定
數(shù)據(jù)變動 ---> 視圖更新
視圖更新 ---> 數(shù)據(jù)變動
要想實現(xiàn)當(dāng)數(shù)據(jù)變動時視圖更新,首先要做的就是如何知道數(shù)據(jù)變動了,可以通過Object.defineProperty()函數(shù)監(jiān)聽data對象里的數(shù)據(jù),當(dāng)數(shù)據(jù)變動了就會觸發(fā)set()方法。所以我們需要實現(xiàn)一個數(shù)據(jù)監(jiān)聽器Observe,來對數(shù)據(jù)對象中的所有屬性進(jìn)行監(jiān)聽,當(dāng)某一屬性數(shù)據(jù)發(fā)生變化時,拿到最新的數(shù)據(jù)通知綁定了該屬性的訂閱器,訂閱器再執(zhí)行相應(yīng)的數(shù)據(jù)更新回調(diào)函數(shù),從而實現(xiàn)視圖的刷新。
當(dāng)設(shè)置this.name = 'hello vue'時,就會執(zhí)行set函數(shù),通知訂閱器里的訂閱者執(zhí)行相應(yīng)的回調(diào)函數(shù),實現(xiàn)數(shù)據(jù)變動,對應(yīng)視圖更新。
function observe(data){
if (typeof data != 'object') {
return ;
}
return new Observe(data);
}
function Observe(data){
this.data = data;
this.walk(data);
}
Observe.prototype = {
walk: function(data){
let _this = this;
for (key in data) {
if (data.hasOwnProperty(key)){
let value = data[key];
if (typeof value == 'object'){
observe(value);
}
_this.defineReactive(data,key,data[key]);
}
}
},
defineReactive: function(data,key,value){
Object.defineProperty(data,key,{
enumerable: true,//可枚舉
configurable: false,//不能再define
get: function(){
console.log('你訪問了' + key);return value;
},
set: function(newValue){
console.log('你設(shè)置了' + key);
if (newValue == value) return;
value = newValue;
observe(newValue);//監(jiān)聽新設(shè)置的值
}
})
}
}
2、實現(xiàn)一個訂閱器
要想通知訂閱者,首先得要有一個訂閱器(統(tǒng)一管理所有的訂閱者)。為了方便管理,我們會為每一個data對象的屬性都添加一個訂閱器(new Dep)。
訂閱器里存著的是訂閱者Watcher(后面會講到),由于訂閱者可能會有多個,我們需要建立一個數(shù)組來維護(hù)。一旦數(shù)據(jù)變化,就會觸發(fā)訂閱器的notify()方法,訂閱者就會調(diào)用自身的update方法實現(xiàn)視圖更新。
function Dep(){
this.subs = [];
}
Dep.prototype = {
addSub: function(sub){this.subs.push(sub);
},
notify: function(){
this.subs.forEach(function(sub) {
sub.update();
})
}
}
每次響應(yīng)屬性的set()函數(shù)調(diào)用的時候,都會觸發(fā)訂閱器,所以代碼補(bǔ)充完整。
Observe.prototype = {
//省略的代碼未作更改
defineReactive: function(data,key,value){
let dep = new Dep();//創(chuàng)建一個訂閱器,會被閉包在key屬性的get/set函數(shù)內(nèi),因此每個屬性對應(yīng)唯一一個訂閱器dep實例
Object.defineProperty(data,key,{
enumerable: true,//可枚舉
configurable: false,//不能再define
get: function(){
console.log('你訪問了' + key);
return value;
},
set: function(newValue){
console.log('你設(shè)置了' + key);
if (newValue == value) return;
value = newValue;
observe(newValue);//監(jiān)聽新設(shè)置的值
dep.notify();//通知所有的訂閱者
}
})
}
}
實現(xiàn)Complie
compile主要做的事情是解析模板指令,將模板中的data屬性替換成data屬性對應(yīng)的值(比如將{{name}}替換成data.name值),然后初始化渲染頁面視圖,并且為每個data屬性添加一個監(jiān)聽數(shù)據(jù)的訂閱者(new Watcher),一旦數(shù)據(jù)有變動,收到通知,更新視圖。
遍歷解析需要替換的根元素el下的HTML標(biāo)簽必然會涉及到多次的DOM節(jié)點操作,因此不可避免的會引發(fā)頁面的重排或重繪,為了提高性能和效率,我們把根元素el下的所有節(jié)點轉(zhuǎn)換為文檔碎片fragment進(jìn)行解析編譯操作,解析完成,再將fragment添加回原來的真實dom節(jié)點中。
注:文檔碎片本身也是一個節(jié)點,但是當(dāng)將該節(jié)點append進(jìn)頁面時,該節(jié)點標(biāo)簽作為根節(jié)點不會顯示html文檔中,其里面的子節(jié)點則可以完全顯示。
Compile解析模板,將模板內(nèi)的子元素#text添加進(jìn)文檔碎片節(jié)點fragment。
function Compile(el,vm){
this.$vm = vm;//vm為當(dāng)前實例
this.$el = document.querySelector(el);//獲得要解析的根元素
if (this.$el){
this.$fragment = this.nodeToFragment(this.$el);
this.init();
this.$el.appendChild(this.$fragment);
}
}
Compile.prototype = {
nodeToFragment: function(el){
let fragment = document.createDocumentFragment();
let child;
while (child = el.firstChild){
fragment.appendChild(child);//append相當(dāng)于剪切的功能
}
return fragment;
},
};
compileElement方法將遍歷所有節(jié)點及其子節(jié)點,進(jìn)行掃描解析編譯,調(diào)用對應(yīng)的指令渲染函數(shù)進(jìn)行數(shù)據(jù)渲染,并調(diào)用對應(yīng)的指令更新函數(shù)進(jìn)行綁定,詳看代碼及注釋說明:
因為我們的模板只含有一個文本節(jié)點#text,因此compileElement方法執(zhí)行后會進(jìn)入_this.compileText(node,reg.exec(node.textContent)[1]);//#text,'name'
Compile.prototype = {
nodeToFragment: function(el){
let fragment = document.createDocumentFragment();
let child;
while (child = el.firstChild){
fragment.appendChild(child);//append相當(dāng)于剪切的功能
}
return fragment;
},
init: function(){
this.compileElement(this.$fragment);
},
compileElement: function(node){
let childNodes = node.childNodes;
const _this = this;
let reg = /\{\{(.*)\}\}/g;
[].slice.call(childNodes).forEach(function(node){
if (_this.isElementNode(node)){//如果為元素節(jié)點,則進(jìn)行相應(yīng)操作
_this.compile(node);
} else if (_this.isTextNode(node) && reg.test(node.textContent)){
//如果為文本節(jié)點,并且包含data屬性(如{{name}}),則進(jìn)行相應(yīng)操作
_this.compileText(node,reg.exec(node.textContent)[1]);//#text,'name'
}
if (node.childNodes && node.childNodes.length){
//如果節(jié)點內(nèi)還有子節(jié)點,則遞歸繼續(xù)解析節(jié)點
_this.compileElement(node);
}
})
},
compileText: function(node,exp){//#text,'name'
compileUtil.text(node,this.$vm,exp);//#text,vm,'name'
},};
CompileText()函數(shù)實現(xiàn)初始化渲染頁面視圖(將data.name的值通過#text.textContent = data.name顯示在頁面上),并且為每個DOM節(jié)點添加一個監(jiān)聽數(shù)據(jù)的訂閱者(這里是為#text節(jié)點新增一個Wather)。
let updater = {
textUpdater: function(node,value){
node.textContent = typeof value == 'undefined' ? '' : value;
},
}
let compileUtil = {
text: function(node,vm,exp){//#text,vm,'name'
this.bind(node,vm,exp,'text');
},
bind: function(node,vm,exp,dir){//#text,vm,'name','text'
let updaterFn = updater[dir + 'Updater'];
updaterFn && updaterFn(node,this._getVMVal(vm,exp));
new Watcher(vm,exp,function(value){
updaterFn && updaterFn(node,value)
});
console.log('加進(jìn)去了');
}
};
現(xiàn)在我們完成了一個能實現(xiàn)文本節(jié)點解析的Compile()函數(shù),接下來我們實現(xiàn)一個Watcher()函數(shù)。
實現(xiàn)Watcher
我們前面講過,Observe()函數(shù)實現(xiàn)data對象的屬性劫持,并在屬性值改變時觸發(fā)訂閱器的notify()通知訂閱者Watcher,訂閱者就會調(diào)用自身的update方法實現(xiàn)視圖更新。
Compile()函數(shù)負(fù)責(zé)解析模板,初始化頁面,并且為每個data屬性新增一個監(jiān)聽數(shù)據(jù)的訂閱者(new Watcher)。
Watcher訂閱者作為Observer和Compile之間通信的橋梁,所以我們可以大致知道Watcher的作用是什么。
主要做的事情是:
在自身實例化時往訂閱器(dep)里面添加自己。
自身必須有一個update()方法 。
待屬性變動dep.notice()通知時,能調(diào)用自身的update()方法,并觸發(fā)Compile中綁定的回調(diào)。
先給出全部代碼,再分析具體的功能。
//Watcher
function Watcher(vm, exp, cb) {
this.vm = vm;
this.cb = cb;
this.exp = exp;
this.value = this.get();//初始化時將自己添加進(jìn)訂閱器
};
Watcher.prototype = {
update: function(){
this.run();
},
run: function(){
const value = this.vm[this.exp];
//console.log('me:'+value);
if (value != this.value){
this.value = value;
this.cb.call(this.vm,value);
}
},
get: function() {
Dep.target = this; // 緩存自己
var value = this.vm[this.exp] // 訪問自己,執(zhí)行defineProperty里的get函數(shù)
Dep.target = null; // 釋放自己
return value;
}
}
//這里列出Observe和Dep,方便理解
Observe.prototype = {
defineReactive: function(data,key,value){
let dep = new Dep();
Object.defineProperty(data,key,{
enumerable: true,//可枚舉
configurable: false,//不能再define
get: function(){
console.log('你訪問了' + key);
//說明這是實例化Watcher時引起的,則添加進(jìn)訂閱器
if (Dep.target){
//console.log('訪問了Dep.target');
dep.addSub(Dep.target);
}
return value;
},
})
}
}
Dep.prototype = {
addSub: function(sub){this.subs.push(sub);
},
}
我們知道在Observe()函數(shù)執(zhí)行時,我們?yōu)槊總€屬性都添加了一個訂閱器dep,而這個dep被閉包在屬性的get/set函數(shù)內(nèi)。所以,我們可以在實例化Watcher時調(diào)用this.get()函數(shù)訪問data.name屬性,這會觸發(fā)defineProperty()函數(shù)內(nèi)的get函數(shù),get方法執(zhí)行的時候,就會在屬性的訂閱器dep添加當(dāng)前watcher實例,從而在屬性值有變化的時候,watcher實例就能收到更新通知。
那么Watcher()函數(shù)中的get()函數(shù)內(nèi)Dep.taeger = this又有什么特殊的含義呢?我們希望的是在實例化Watcher時將相應(yīng)的Watcher實例添加一次進(jìn)dep訂閱器即可,而不希望在以后每次訪問data.name屬性時都加入一次dep訂閱器。所以我們在實例化執(zhí)行this.get()函數(shù)時用Dep.target = this來標(biāo)識當(dāng)前Watcher實例,當(dāng)添加進(jìn)dep訂閱器后設(shè)置Dep.target=null。
實現(xiàn)VMVM
MVVM作為數(shù)據(jù)綁定的入口,整合Observer、Compile和Watcher三者,通過Observer來監(jiān)聽自己的model數(shù)據(jù)變化,通過Compile來解析編譯模板指令,最終利用Watcher搭起Observer和Compile之間的通信橋梁,達(dá)到數(shù)據(jù)變化 -> 視圖更新;視圖交互變化(input) -> 數(shù)據(jù)model變更的雙向綁定效果。
function MVVM(options) {
this.$options = options || {};
var data = this._data = this.$options.data;
var _this = this;
// 數(shù)據(jù)代理
// 實現(xiàn) vm._data.xxx -> vm.xxx
Object.keys(data).forEach(function(key) {
_this._proxyData(key);
});
observe(data, this);
this.$compile = new Compile(options.el || document.body, this);
}
相關(guān)文章
Vue導(dǎo)入excel文件的兩種方式(form表單和el-upload)
最近開發(fā)遇到一個點擊導(dǎo)入按鈕讓excel文件數(shù)據(jù)導(dǎo)入的需求,下面這篇文章主要給大家介紹了關(guān)于Vue導(dǎo)入excel文件的兩種方式,分別是form表單和el-upload兩種方法,需要的朋友可以參考下2022-11-11
lottie實現(xiàn)vue自定義loading指令及常用指令封裝詳解
這篇文章主要為大家介紹了lottie實現(xiàn)vue自定義loading指令及常用指令封裝,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09
vue組件 keep-alive 和 transition 使用詳解
這篇文章主要介紹了vue組件 keep-alive 和 transition 使用詳解,需要的朋友可以參考下2019-10-10
結(jié)合mint-ui移動端下拉加載實踐方法總結(jié)
下面小編就為大家?guī)硪黄Y(jié)合mint-ui移動端下拉加載實踐方法總結(jié)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-11-11
vue el-tree 默認(rèn)展開第一個節(jié)點的實現(xiàn)代碼
這篇文章主要介紹了vue el-tree 默認(rèn)展開第一個節(jié)點的實現(xiàn)代碼,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-05-05
基于Vue3+Element Plus 實現(xiàn)多表單校驗demo
表單校驗在日常的開發(fā)需求中是一種很常見的需求,通常在提交表單發(fā)起請求前校驗用戶輸入是否符合規(guī)則,通常只需formRef.value.validate()即可校驗,本文給大家介紹基于Vue3+Element Plus 實現(xiàn)多表單校驗demo,感興趣的朋友一起看看吧2024-06-06

