干貨丨JavaScript如何實現(xiàn)一個簡單的Vue

Object.defineProperty()

實現(xiàn)之前我們得先看一下Object.defineProperty的實現(xiàn),因為vue主要是通過數(shù)據(jù)劫持來實現(xiàn)的,通過get、set來完成數(shù)據(jù)的讀取和更新。

var obj = {name:'wclimb'}

var age = 24

Object.defineProperty(obj,'age',{

enumerable: true, // 可枚舉

configurable: false, // 不能再define

get () {

return age

},

set (newVal) {

console.log('我改變了',age +' -> '+newVal);

age = newVal

}

})

> obj.age

> 24

> obj.age = 25;

> 我改變了 24 -> 25

> 25

從上面可以看到通過get獲取數(shù)據(jù),通過set監(jiān)聽到數(shù)據(jù)變化執(zhí)行相應(yīng)操作,還是不明白的話可以去看看Object.defineProperty文檔。

流程圖

html代碼結(jié)構(gòu)

<div id="wrap">

<p v-html="test"></p>

<input type="text" v-model="form">

<input type="text" v-model="form">

<button @click="changeValue">改變值</button>

{{form}}

</div>

Vue結(jié)構(gòu)

class Vue{

constructor(){}

proxyData(){}

observer(){}

compile(){}

compileText(){}

}

class Watcher{

constructor(){}

update(){}

}

Vue constructor 構(gòu)造函數(shù)主要是數(shù)據(jù)的初始化

proxyData 數(shù)據(jù)代理

observer 劫持監(jiān)聽所有數(shù)據(jù)

compile 解析dom

compileText 解析dom里處理純雙花括號的操作

Watcher 更新視圖操作

Vue constructor 初始化

class Vue{

constructor(options = {}){

this.$el = document.querySelector(options.el);

let data = this.data = options.data;

// 代理data,使其能直接this.xxx的方式訪問data,正常的話需要this.data.xxx

Object.keys(data).forEach((key)=> {

this.proxyData(key);

});

this.methods = obj.methods // 事件方法

this.watcherTask = {}; // 需要監(jiān)聽的任務(wù)列表

this.observer(data); // 初始化劫持監(jiān)聽所有數(shù)據(jù)

this.compile(this.$el); // 解析dom

}

}

上面主要是初始化操作,針對傳過來的數(shù)據(jù)進行處理

proxyData 代理data

class Vue{

constructor(options = {}){

......

}

proxyData(key){

let that = this;

Object.defineProperty(that, key, {

configurable: false,

enumerable: true,

get () {

return that.data[key];

},

set (newVal) {

that.data[key] = newVal;

}

});

}

}

上面主要是代理data到最上層,this.xxx的方式直接訪問data

observer 劫持監(jiān)聽

class Vue{

constructor(options = {}){

......

}

proxyData(key){

......

}

observer(data){

let that = this

Object.keys(data).forEach(key=>{

let value = data[key]

this.watcherTask[key] = []

Object.defineProperty(data,key,{

configurable: false,

enumerable: true,

get(){

return value

},

set(newValue){

if(newValue !== value){

value = newValue

that.watcherTask[key].forEach(task => {

task.update()

})

}

}

})

})

}

}

同樣是使用Object.defineProperty來監(jiān)聽數(shù)據(jù),初始化需要訂閱的數(shù)據(jù)。

把需要訂閱的數(shù)據(jù)到push到watcherTask里,等到時候需要更新的時候就可以批量更新數(shù)據(jù)了。??下面就是;

遍歷訂閱池,批量更新視圖。

set(newValue){

if(newValue !== value){

value = newValue

// 批量更新視圖

that.watcherTask[key].forEach(task => {

task.update()

})

}

}

compile 解析dom

class Vue{

constructor(options = {}){

......

}

proxyData(key){

......

}

observer(data){

......

}

compile(el){

var nodes = el.childNodes;

for (let i = 0; i < nodes.length; i++) {

const node = nodes[i];

if(node.nodeType === 3){

var text = node.textContent.trim();

if (!text) continue;

this.compileText(node,'textContent')

}else if(node.nodeType === 1){

if(node.childNodes.length > 0){

this.compile(node)

}

if(node.hasAttribute('v-model') && (node.tagName === 'INPUT' || node.tagName === 'TEXTAREA')){

node.addEventListener('input',(()=>{

let attrVal = node.getAttribute('v-model')

this.watcherTask[attrVal].push(new Watcher(node,this,attrVal,'value'))

node.removeAttribute('v-model')

return () => {

this.data[attrVal] = node.value

}

})())

}

if(node.hasAttribute('v-html')){

let attrVal = node.getAttribute('v-html');

this.watcherTask[attrVal].push(new Watcher(node,this,attrVal,'innerHTML'))

node.removeAttribute('v-html')

}

this.compileText(node,'innerHTML')

if(node.hasAttribute('@click')){

let attrVal = node.getAttribute('@click')

node.removeAttribute('@click')

node.addEventListener('click',e => {

this.methods[attrVal] && this.methods[attrVal].bind(this)()

})

}

}

}

},

compileText(node,type){

let reg = /{{(.*)}}/g, txt = node.textContent;

if(reg.test(txt)){

node.textContent = txt.replace(reg,(matched,value)=>{

let tpl = this.watcherTask[value] || []

tpl.push(new Watcher(node,this,value,type))

return value.split('.').reduce((val, key) => {

return this.data[key];

}, this.$el);

})

}

}

}

這里代碼比較多,我們拆分看你就會覺得很簡單了

首先我們先遍歷el元素下面的所有子節(jié)點,node.nodeType === 3 的意思是當(dāng)前元素是文本節(jié)點,node.nodeType === 1 的意思是當(dāng)前元素是元素節(jié)點。因為可能有的是純文本的形式,如純雙花括號就是純文本的文本節(jié)點,然后通過判斷元素節(jié)點是否還存在子節(jié)點,如果有的話就遞歸調(diào)用compile方法。下面重頭戲來了,我們拆開看:

if(node.hasAttribute('v-html')){

let attrVal = node.getAttribute('v-html');

this.watcherTask[attrVal].push(new Watcher(node,this,attrVal,'innerHTML'))

node.removeAttribute('v-html')

}

上面這個首先判斷node節(jié)點上是否有v-html這種指令,如果存在的話,我們就發(fā)布訂閱,怎么發(fā)布訂閱呢?只需要把當(dāng)前需要訂閱的數(shù)據(jù)push到watcherTask里面,然后到時候在設(shè)置值的時候就可以批量更新了,實現(xiàn)雙向數(shù)據(jù)綁定,也就是下面的操作

that.watcherTask[key].forEach(task => {

task.update()

})

然后push的值是一個Watcher的實例,首先他new的時候會先執(zhí)行一次,執(zhí)行的操作就是去把純雙花括號 -> 1,也就是說把我們寫好的模板數(shù)據(jù)更新到模板視圖上。

最后把當(dāng)前元素屬性剔除出去,我們用Vue的時候也是看不到這種指令的,不剔除也不影響

至于Watcher是什么,看下面就知道了

Watcher

that.watcherTask[key].forEach(task => {

task.update()

})

之前發(fā)布訂閱之后走了這里面的操作,意思就是把當(dāng)前元素如:node.innerHTML = '這是data里面的值'、node.value = '這個是表單的數(shù)據(jù)'

那么我們?yōu)槭裁床恢苯尤ジ履兀€需要update做什么,不是多此一舉嗎?

其實update記得嗎?我們在訂閱池里面需要批量更新,就是通過調(diào)用Watcher原型上的update方法。

Java高架構(gòu)師、分布式架構(gòu)、高可擴展、高性能、高并發(fā)、性能優(yōu)化、Spring boot、Redis、ActiveMQ、Nginx、Mycat、Netty、Jvm大型分布式項目實戰(zhàn)學(xué)習(xí)架構(gòu)師視頻免費獲取架構(gòu)群:854180697? ??加群鏈接

寫在最后:歡迎留言討論,加關(guān)注,持續(xù)更新!

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

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

  • vue的使用相信大家都很熟練了,使用起來簡單。但是大部分人不知道其內(nèi)部的原理是怎么樣的,今天我們就來一起實現(xiàn)一個簡...
    天as痕閱讀 503評論 0 0
  • vue理解淺談 一 理解vue的核心理念 使用vue會讓人感到身心愉悅,它同時具備angular和react的優(yōu)點...
    ndxs2008閱讀 24,404評論 2 18
  • 本文是lhyt本人原創(chuàng),希望用通俗易懂的方法來理解一些細節(jié)和難點。轉(zhuǎn)載時請注明出處。文章最早出現(xiàn)于本人github...
    lhyt閱讀 2,296評論 0 4
  • 下午放學(xué)后,一連接到幾個家長的投訴信息。一個是當(dāng)面和我交談的喬同學(xué)的媽媽,她特意在周五放學(xué)時自己來接孩子,因為平時...
    陌上桑蘭閱讀 292評論 0 1
  • 孩子:媽媽,再給我講一個案子吧! 媽媽:講個什么呢?再講一個媽媽處理的借錢的案子? 孩子:嗯嗯! 媽媽:假如我是原...
    wshmother閱讀 565評論 0 2

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