教你擼一個簡單的Vue
摘要:你會實現一個Vue嗎?
- 原文: ofollow,noindex">JavaScript之實現一個簡單的Vue
- 地址: https://segmentfault.com/a/1190000016365102
- 作者: wclimb
Fundebug經授權轉載,版權歸原作者所有。
vue的使用相信大家都很熟練了,使用起來簡單。但是大部分人不知道其內部的原理是怎麼樣的,今天我們就來一起實現一個簡單的vue
Object.defineProperty()
實現之前我們得先看一下 JavaScript/Reference/Global_Objects/Object/defineProperty" target="_blank" rel="nofollow,noindex">Object.defineProperty 的實現,因為vue主要是通過資料劫持來實現的,通過 get
、 set
來完成資料的讀取和更新。
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
獲取資料,通過 set
監聽到資料變化執行相應操作,還是不明白的話可以去看看 Object.defineProperty 文件。
流程圖
html程式碼結構
<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>
js呼叫
new Vue({ el: '#wrap', data:{ form: '這是form的值', test: '<strong>我是粗體</strong>', }, methods:{ changeValue(){ console.log(this.form) this.form = '值被我改變了,氣不氣?' } } })
Vue結構
class Vue{ constructor(){} proxyData(){} observer(){} compile(){} compileText(){} } class Watcher{ constructor(){} update(){} }
-
Vue constructor
建構函式主要是資料的初始化 -
proxyData
資料代理 -
observer
劫持監聽所有資料 -
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 = options.methods // 事件方法 this.watcherTask = {}; // 需要監聽的任務列表 this.observer(data); // 初始化劫持監聽所有資料 this.compile(this.$el); // 解析dom } }
上面主要是初始化操作,針對傳過來的資料進行處理
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 劫持監聽
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
來監聽資料,初始化需要訂閱的資料。
把需要訂閱的資料到 push
到 watcherTask
裡,等到時候需要更新的時候就可以批量更新資料了下面就是;
遍歷訂閱池,批量更新檢視。
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)) if(value.split('.').length > 1){ let v = null value.split('.').forEach((val,i)=>{ v = !v ? this[val] : v[val] }) return v }else{ return this[value] } }) } } }
這裡程式碼比較多,我們拆分看你就會覺得很簡單了
首先我們先遍歷 el
元素下面的所有子節點, node.nodeType === 3
的意思是當前元素是文字節點, node.nodeType === 1
的意思是當前元素是元素節點。因為可能有的是純文字的形式,如 純雙花括號
就是純文字的文字節點,然後通過判斷元素節點是否還存在子節點,如果有的話就遞迴呼叫 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節點上是否有 v-html
這種指令,如果存在的話,我們就釋出訂閱,怎麼釋出訂閱呢?只需要把當前需要訂閱的資料 push
到 watcherTask
裡面,然後到時候在設定值的時候就可以批量更新了,實現雙向資料繫結,也就是下面的操作
that.watcherTask[key].forEach(task => { task.update() })
然後 push
的值是一個 Watcher
的例項,首先他new的時候會先執行一次,執行的操作就是去把 純雙花括號
-> 1,也就是說把我們寫好的模板資料更新到模板檢視上。
最後把當前元素屬性剔除出去,我們用 Vue
的時候也是看不到這種指令的,不剔除也不影響
至於 Watcher
是什麼,看下面就知道了
Watcher
class Watcher{ constructor(el,vm,value,type){ this.el = el; this.vm = vm; this.value = value; this.type = type; this.update() } update(){ this.el[this.type] = this.vm.data[this.value] } }
之前釋出訂閱之後走了這裡面的操作,意思就是把當前元素如:node.innerHTML = ‘這是data裡面的值’、node.value = ‘這個是表單的資料’
那麼我們為什麼不直接去更新呢,還需要 update
做什麼,不是多此一舉嗎?
其實 update
記得嗎?我們在訂閱池裡面需要批量更新,就是通過呼叫 Watcher
原型上的 update
方法。
效果
線上效果地址 ,大家可以瀏覽器看一下效果,由於本人太懶了, gif
效果圖就先不放了,哈哈。
完整程式碼
完整程式碼已經放到 github
上了 -> MyVue
參考
關於Fundebug
Fundebug專注於JavaScript、微信小程式、微信小遊戲、支付寶小程式、React Native、Node.js和Java實時BUG監控。 自從2016年雙十一正式上線,Fundebug累計處理了6億+錯誤事件,得到了Google、360、金山軟體等眾多知名使用者的認可。歡迎免費試用!