2021年,讓我們手寫一個mini版本的vue2.x和vue3.x框架
作者:夕水
來源:SegmentFault 思否社區(qū)
mini版本的vue.js2.X版本框架
模板代碼
首先我們看一下我們要實現(xiàn)的模板代碼:
<div id="app">
<h3>{{ msg }}</h3>
<p>{{ count }}</p>
<h1>v-text</h1>
<p v-text="msg"></p>
<input type="text" v-model="count">
<button type="button" v-on:click="increase">add+</button>
<button type="button" v-on:click="changeMessage">change message!</button>
<button type="button" v-on:click="recoverMessage">recoverMessage!</button>
</div>
邏輯代碼
然后就是我們要編寫的javascript代碼。
const app = new miniVue({
el:"#app",
data:{
msg:"hello,mini vue.js",
count:666
},
methods:{
increase(){
this.count++;
},
changeMessage(){
this.msg = "hello,eveningwater!";
},
recoverMessage(){
console.log(this)
this.msg = "hello,mini vue.js";
}
}
});
運行效果
我們來看一下實際運行效果如下所示:

源碼實現(xiàn)-2.x
miniVue類
mini-vue,那么我們先定義一個類,并且它的參數(shù)一定是一個屬性配置對象。如下: class miniVue {
constructor(options = {}){
//后續(xù)要做的事情
}
}
//在miniVue構(gòu)造函數(shù)的內(nèi)部
//保存根元素,能簡便就盡量簡便,不考慮數(shù)組情況
this.$el = typeof options.el === 'string' ? document.querySelector(options.el) : options.el;
this.$methods = options.methods;
this.$data = options.data;
this.$options = options;
代理數(shù)據(jù)
//this.$data.xxx -> this.xxx;
//proxy代理實例上的data對象
proxy(data){
//后續(xù)代碼
}
Object.defineProperty,通過這個方法來完成這個代理方法。如下://proxy方法內(nèi)部
// 因為我們是代理每一個屬性,所以我們需要將所有屬性拿到
Object.keys(data).forEach(key => {
Object.defineProperty(this,key,{
enumerable:true,
configurable:true,
get:() => {
return data[key];
},
set:(newValue){
//這里我們需要判斷一下如果值沒有做改變就不用賦值,需要排除NaN的情況
if(newValue === data[key] || _isNaN(newValue,data[key]))return;
data[key] = newValue;
}
})
})
_isNaN工具方法的實現(xiàn),如下:function _isNaN(a,b){
return Number.isNaN(a) && Number.isNaN(b);
}
// 構(gòu)造函數(shù)內(nèi)部
this.proxy(this.$data);
數(shù)據(jù)響應(yīng)式觀察者observer類
Observer。如下:class Observer {
constructor(data){
//后續(xù)實現(xiàn)
}
}
Object.defineProperty方法,我們需要在getter函數(shù)中收集依賴,在setter函數(shù)中發(fā)送通知,用來通知依賴進(jìn)行更新。我們用一個方法來專門去執(zhí)行定義響應(yīng)式對象的方法,叫walk,如下://再次申明,不考慮數(shù)組,只考慮對象
walk(data){
if(typeof data !== 'object' || !data)return;
// 數(shù)據(jù)的每一個屬性都調(diào)用定義響應(yīng)式對象的方法
Object.keys(data).forEach(key => this.defineReactive(data,key,data[key]));
}
defineReactive方法的實現(xiàn),同樣也是使用Object.defineProperty方法來定義響應(yīng)式對象,如下所示:defineReactive(data,key,value){
// 獲取當(dāng)前this,以避免后續(xù)用vm的時候,this指向不對
const vm = this;
// 遞歸調(diào)用walk方法,因為對象里面還有可能是對象
this.walk(value);
//實例化收集依賴的類
let dep = new Dep();
Object.defineProperty(data,key,{
enumerable:true,
configurable:true,
get(){
// 收集依賴,依賴存在Dep類上
Dep.target && Dep.add(Dep.target);
return value;
},
set(newValue){
// 這里也判斷一下
if(newValue === value || __isNaN(value,newValue))return;
// 否則改變值
value = newValue;
// newValue也有可能是對象,所以遞歸
vm.walk(newValue);
// 通知Dep類
dep.notify();
}
})
}
Observer類完成了之后,我們需要在miniVue類的構(gòu)造函數(shù)中實例化一下它,如下://在miniVue構(gòu)造函數(shù)內(nèi)部
new Observer(this.$data);
依賴類
defineReactive方法內(nèi)部用到了Dep類,接下來,我們來定義這個類。如下:class Dep {
constructor(){
//后續(xù)代碼
}
}
defineReactive中,我們很明顯就知道會有add方法和notify方法,并且我們需要一種數(shù)據(jù)結(jié)構(gòu)來存儲依賴,vue源碼用的是隊列,而在這里為了簡單化,我們使用ES6的set數(shù)據(jù)結(jié)構(gòu)。如下://構(gòu)造函數(shù)內(nèi)部
this.deps = new Set();
add方法和notify方法,事實上這里還會有刪除依賴的方法,但是這里為了最簡便,我們只需要一個add和notify方法即可。如下:add(dep){
//判斷dep是否存在并且是否存在update方法,然后添加到存儲的依賴數(shù)據(jù)結(jié)構(gòu)中
if(dep && dep.update)this.deps.add(dep);
}
notify(){
// 發(fā)布通知無非是遍歷一道dep,然后調(diào)用每一個dep的update方法,使得每一個依賴都會進(jìn)行更新
this.deps.forEach(dep => dep.update())
}
Watcher類
Watcher。class Watcher {
//3個參數(shù),當(dāng)前組件實例vm,state也就是數(shù)據(jù)以及一個回調(diào)函數(shù),或者叫處理器
constructor(vm,key,cb){
//后續(xù)代碼
}
}
Watcher的用法,我們是不是會像如下這樣來寫://3個參數(shù),當(dāng)前組件實例vm,state也就是數(shù)據(jù)以及一個回調(diào)函數(shù),或者叫處理器
new Watcher(vm,key,cb);
//構(gòu)造函數(shù)內(nèi)部
this.vm = vm;
this.key = key;
this.cb = cb;
//依賴類
Dep.target = this;
// 我們用一個變量來存儲舊值,也就是未變更之前的值
this.__old = vm[key];
Dep.target = null;
update(){
//獲取新的值
let newValue = this.vm[this.key];
//與舊值做比較,如果沒有改變就無需執(zhí)行下一步
if(newValue === this.__old || __isNaN(newValue,this.__old))return;
//把新的值回調(diào)出去
this.cb(newValue);
//執(zhí)行完之后,需要更新一下舊值的存儲
this.__old = newValue;
}
編譯類compiler類
初始化
class Compiler {
constructor(vm){
//后續(xù)代碼
}
}
//在miniVue構(gòu)造函數(shù)內(nèi)部
new Compiler(this);
//編譯類構(gòu)造函數(shù)內(nèi)部
//根元素
this.el = vm.$el;
//事件方法
this.methods = vm.$methods;
//當(dāng)前組件實例
this.vm = vm;
//調(diào)用編譯函數(shù)開始編譯
this.compile(vm.$el);
compile方法
compile(el){
//拿到所有子節(jié)點(包含文本節(jié)點)
let childNodes = el.childNodes;
//轉(zhuǎn)成數(shù)組
Array.from(childNodes).forEach(node => {
//判斷是文本節(jié)點還是元素節(jié)點分別執(zhí)行不同的編譯方法
if(this.isTextNode(node)){
this.compileText(node);
}else if(this.isElementNode(node)){
this.compileElement(node);
}
//遞歸判斷node下是否還含有子節(jié)點,如果有的話繼續(xù)編譯
if(node.childNodes && node.childNodes.length)this.compile(node);
})
}
isTextNode(node){
return node.nodeType === 3;
}
isElementNode(node){
return node.nodeType === 3;
}
編譯文本節(jié)點
compileText編譯文本節(jié)點的方法。如下://{{ count }}數(shù)據(jù)結(jié)構(gòu)是類似如此的
compileText(node){
//后續(xù)代碼
}
{{ count }}映射成為0,而文本節(jié)點不就是node.textContent屬性嗎?所以此時我們可以想到根據(jù)正則來匹配{{}}中的count值,然后對應(yīng)替換成數(shù)據(jù)中的count值,然后我們再調(diào)用一次Watcher類,如果更新了,就再次更改這個node.textContent的值。如下:compileText(node){
//定義正則,匹配{{}}中的count
let reg = /\{\{(.+?)\}\}/g;
let value = node.textContent;
//判斷是否含有{{}}
if(reg.test(value)){
//拿到{{}}中的count,由于我們是匹配一個捕獲組,所以我們可以根據(jù)RegExp類的$1屬性來獲取這個count
let key = RegExp.$1.trim();
node.textContent = value.replace(reg,this.vm[key]);
//如果更新了值,還要做更改
new Watcher(this.vm,key,newValue => {
node.textContent = newValue;
})
}
}
編譯元素節(jié)點
指令
v-text,v-model,v-on:click這三個指令。讓我們來看看compileElement方法吧。compileElement(node){
//指令不就是一堆屬性嗎,所以我們只需要獲取屬性即可
const attrs = node.attributes;
if(attrs.length){
Array.from(attrs).forEach(attr => {
//這里由于我們拿到的attributes可能包含不是指令的屬性,所以我們需要先做一次判斷
if(this.isDirective(attr)){
//根據(jù)v-來截取一下后綴屬性名,例如v-on:click,subStr(5)即可截取到click,v-text與v-model則subStr(2)截取到text和model即可
let attrName = attr.indexOf(':') > -1 ? attr.subStr(5) : attr.subStr(2);
let key = attr.value;
//單獨定義一個update方法來區(qū)分這些
this.update(node,attrName,key,this.vm[key]);
}
})
}
}
isDirective輔助方法,我們可以使用startsWith方法,判斷是否含有v-值即可認(rèn)定這個屬性就是一個指令。如下:isDirective(dir){
return dir.startsWith('v-');
}
update方法。如下:update(node,attrName,key,value){
//后續(xù)代碼
}
//update函數(shù)內(nèi)部
if(attrName === 'text'){
//執(zhí)行v-text的操作
}else if(attrName === 'model'){
//執(zhí)行v-model的操作
}else if(attrName === 'click'){
//執(zhí)行v-on:click的操作
}
v-text指令
//attrName === 'text'內(nèi)部
node.textContent = value;
new Watcher(this.vm,key,newValue => {
node.textContent = newValue;
})
v-model指令
//attrName === 'model'內(nèi)部
node.value = value;
new Watcher(this.vm,key,newValue => {
node.value = newValue;
});
node.addEventListener('input',(e) => {
this.vm[key] = node.value;
})
v-on:click指令
//attrName === 'click'內(nèi)部
node.addEventListener(attrName,this.methods[key].bind(this.vm));
mini版本的vue.js3.x框架
模板代碼
<div id="app"></div>
邏輯代碼
const App = {
$data:null,
setup(){
let count = ref(0);
let time = reactive({ second:0 });
let com = computed(() => `${ count.value + time.second }`);
setInterval(() => {
time.second++;
},1000);
setInterval(() => {
count.value++;
},2000);
return {
count,
time,
com
}
},
render(){
return `
<h1>How reactive?</h1>
<p>this is reactive work:${ this.$data.time.second }</p>
<p>this is ref work:${ this.$data.count.value }</p>
<p>this is computed work:${ this.$data.com.value }</p>
`
}
}
mount(App,document.querySelector("#app"));
運行效果

思考一下,我們要實現(xiàn)如上的功能應(yīng)該怎么做呢?
源碼實現(xiàn)-3.x
與vue2.x做比較
effect。vue3.x更像是函數(shù)式編程了,每一個功能都是一個函數(shù),比如定義響應(yīng)式對象,那就是reactive方法,再比如computed,同樣的也是computed方法...廢話不多說,讓我們來看一下吧!reactive方法
function reactive(data){
if(!isObject(data))return;
//后續(xù)代碼
}
function reactive(data){
if(!isObject(data))return;
return new Proxy(data,{
get(target,key,receiver){
//反射api
const ret = Reflect.get(target,key,receiver);
//收集依賴
track(target,key);
return isObject(ret) ? reactive(ret) : ret;
},
set(target,key,val,receiver){
Reflect.set(target,key,val,receiver);
//觸發(fā)依賴方法
trigger(target,key);
return true;
},
deleteProperty(target,key,receiver){
const ret = Reflect.deleteProperty(target,key,receiver);
trigger(target,key);
return ret;
}
})
}
track方法
//全局變量表示依賴
let activeEffect;
//存儲依賴的數(shù)據(jù)結(jié)構(gòu)
let targetMap = new WeakMap();
//每一個依賴又是一個map結(jié)構(gòu),每一個map存儲一個副作用函數(shù)即effect函數(shù)
function track(target,key){
//拿到依賴
let depsMap = targetMap.get(target);
// 如果依賴不存在則初始化
if(!depsMap)targetMap.set(target,(depsMap = new Map()));
//拿到具體的依賴,是一個set結(jié)構(gòu)
let dep = depsMap.get(key);
if(!dep)depsMap.set(key,(dep = new Set()));
//如果沒有依賴,則存儲再set數(shù)據(jù)結(jié)構(gòu)中
if(!dep.has(activeEffect))dep.add(activeEffect)
}
trigger方法
function trigger(target,key){
const depsMap = targetMap.get(target);
//存儲依賴的數(shù)據(jù)結(jié)構(gòu)都拿不到,則代表沒有依賴,直接返回
if(!depsMap)return;
depsMap.get(key).forEach(effect => effect && effect());
}
effect方法
function effect(handler,options = {}){
const __effect = function(...args){
activeEffect = __effect;
return handler(...args);
}
//配置對象有一個lazy屬性,用于computed計算屬性的實現(xiàn),因為計算屬性是懶加載的,也就是延遲執(zhí)行
//也就是說如果不是一個計算屬性的回調(diào)函數(shù),則立即執(zhí)行副作用函數(shù)
if(!options.lazy){
__effect();
}
return __effect;
}
computed的實現(xiàn)
function computed(handler){
// 只考慮函數(shù)的情況
// 延遲計算 const c = computed(() => `${ count.value}!`)
let _computed;
//可以看到computed就是一個添加了lazy為true的配置對象的副作用函數(shù)
const run = effect(handler,{ lazy:true });
_computed = {
//get 訪問器
get value(){
return run();
}
}
return _computed;
}
ref方法
const count = ref(0);
//修改
count.value = 1;
function ref(target){
let value = target;
const obj = {
get value(){
//收集依賴
track(obj,'value');
return value;
},
set value(newValue){
if(value === newValue)return;
value = newValue;
//觸發(fā)依賴
trigger(obj,'value');
}
}
return obj;
}
mount方法
function mount(instance,el){
effect(function(){
instance.$data && update(instance,el);
});
//setup返回的數(shù)據(jù)就是實例上的數(shù)據(jù)
instance.$data = instance.setup();
//這里的update實際上就是編譯函數(shù)
update(instance,el);
}
update編譯函數(shù)
innerHTML。如下://這是最簡單的編譯函數(shù)
function update(instance,el){
el.innerHTML = instance.render();
}

評論
圖片
表情
