用了兩年左右的vue,雖然看過vue的源碼,推薦黃軼大佬的vue源碼分析,至關到位。從頭梳理了vue的實現過程。週末又看了一個公開課的vue源碼分析,想着本身是否是也能夠寫一個來實現,說幹就幹,開始coding!
目前最新版本的vue內部依然使用了Object.defineProperty()來實現對數據屬性的劫持,進而達到監聽數據變更的效果。html
相信看過vue官網的小夥伴們必定看過下面這張圖吧,解釋了vue是如何實現響應式的數據綁定。vue
主要利用了Object.defineProperty()這個方法,對數據進行遍歷,給每個對象都添加了getter()和setter().主要代碼以下:node
class Observer{ constructor(data){ this.data=data; this.traverse(data); } traverse(data) { var self = this; Object.keys(data).forEach(function(key) { self.convert(key, data[key]); }); } convert(key,val){ this.defineReactive(this.data, key, val); } defineReactive(data, key, val) { var dep = new Dep(); var childObj = observe(val); Object.defineProperty(data, key, { enuselfrable: true, // 可枚舉 configurable: false, // 不能再define get(){ if (Dep.target) { dep.depend(); } return val; }, set(newVal) { if (newVal === val) { return; } val = newVal; // 新的值是object的話,進行監聽 childObj = observe(newVal); // 通知訂閱者 dep.notify(); } }); } } function observe(value, vm) { if (!value || typeof value !== 'object') { return; } return new Observer(value); }
通過以上的方法,咱們就劫持到了數據屬性。git
主要用來解析各類指令,好比v-modal,v-on:click等指令。而後將模版中的變量替換成數據,渲染view,將每一個指令對應的節點綁定更新函數,添加監聽數據的訂閱者,一旦數據發生變更,收到通知,更新視圖。github
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); } } node2Fragment(el){ var fragment = document.createDocumentFragment(), child; // 將原生節點拷貝到fragment while (child = el.firstChild) { fragment.appendChild(child); } return fragment; } init(){ this.compileElement(this.$fragment); } compileElement(el){ var childNodes = el.childNodes, self = this; [].slice.call(childNodes).forEach(function(node) { var text = node.textContent; var reg = /\{\{(.*)\}\}/; if (self.isElementNode(node)) { self.compile(node); } else if (self.isTextNode(node) && reg.test(text)) { self.compileText(node, RegExp.$1); } if (node.childNodes && node.childNodes.length) { self.compileElement(node); } }); } compile(node){ var nodeAttrs = node.attributes, self = this; [].slice.call(nodeAttrs).forEach(function(attr) { var attrName = attr.name; if (self.isDirective(attrName)) { var exp = attr.value; var dir = attrName.substring(2); // 事件指令 if (self.isEventDirective(dir)) { compileUtil.eventHandler(node, self.$vm, exp, dir); // 普通指令 } else { compileUtil[dir] && compileUtil[dir](node, self.$vm, exp); } node.removeAttribute(attrName); } }); } compileText(node, exp){ compileUtil.text(node, this.$vm, exp); } isDirective(attr){ return attr.indexOf('v-') == 0; } isEventDirective(dir){ return dir.indexOf('on') === 0; } isElementNode(node){ return node.nodeType == 1; } isTextNode(node){ return node.nodeType == 3; } } // 指令處理集合 var compileUtil = { text: function(node, vm, exp) { this.bind(node, vm, exp, 'text'); }, html: function(node, vm, exp) { this.bind(node, vm, exp, 'html'); }, model: function(node, vm, exp) { this.bind(node, vm, exp, 'model'); var self = this, val = this._getVMVal(vm, exp); node.addEventListener('input', function(e) { var newValue = e.target.value; if (val === newValue) { return; } self._setVMVal(vm, exp, newValue); val = newValue; }); }, class: function(node, vm, exp) { this.bind(node, vm, exp, 'class'); }, bind: function(node, vm, exp, dir) { var updaterFn = updater[dir + 'Updater']; updaterFn && updaterFn(node, this._getVMVal(vm, exp)); new Watcher(vm, exp, function(value, oldValue) { updaterFn && updaterFn(node, value, oldValue); }); }, // 事件處理 eventHandler: function(node, vm, exp, dir) { var eventType = dir.split(':')[1], fn = vm.$options.methods && vm.$options.methods[exp]; if (eventType && fn) { node.addEventListener(eventType, fn.bind(vm), false); } }, _getVMVal: function(vm, exp) { var val = vm; exp = exp.split('.'); exp.forEach(function(k) { val = val[k]; }); return val; }, _setVMVal: function(vm, exp, value) { var val = vm; exp = exp.split('.'); exp.forEach(function(k, i) { // 非最後一個key,更新val的值 if (i < exp.length - 1) { val = val[k]; } else { val[k] = value; } }); } }; var updater = { textUpdater: function(node, value) { node.textContent = typeof value == 'undefined' ? '' : value; }, htmlUpdater: function(node, value) { node.innerHTML = typeof value == 'undefined' ? '' : value; }, classUpdater: function(node, value, oldValue) { var className = node.className; className = className.replace(oldValue, '').replace(/\s$/, ''); var space = className && String(value) ? ' ' : ''; node.className = className + space + value; }, modelUpdater: function(node, value, oldValue) { node.value = typeof value == 'undefined' ? '' : value; } };
做爲連接的橋樑,連接了compile和observer。添加訂閱者,當檢測到屬性發生變化,接收到dep.notify()的通知的時候,就執行自身的update()方法chrome
class Watcher{ constructor(vm, expOrFn, cb){ this.cb = cb; this.vm = vm; this.expOrFn = expOrFn; this.depIds = {}; if (typeof expOrFn === 'function') { this.getter = expOrFn; } else { this.getter = this.parseGetter(expOrFn); } this.value = this.get(); } update(){ this.run(); } run(){ var value = this.get(); var oldVal = this.value; if (value !== oldVal) { this.value = value; this.cb.call(this.vm, value, oldVal); } } addDep(dep){ if (!this.depIds.hasOwnProperty(dep.id)) { dep.addSub(this); this.depIds[dep.id] = dep; } } get() { Dep.target = this; var value = this.getter.call(this.vm, this.vm); Dep.target = null; return value; } parseGetter(exp){ if (/[^\w.$]/.test(exp)) return; var exps = exp.split('.'); return function(obj) { for (var i = 0, len = exps.length; i < len; i++) { if (!obj) return; obj = obj[exps[i]]; } return obj; } } }
MVVM做爲數據綁定的入口,整合Observer、Compile和Watcher三者,經過Observer來監聽本身的model數據變化,經過Compile來解析編譯模板指令,最終利用Watcher搭起Observer和Compile之間的通訊橋樑,達到數據變化,觸發視圖更新;視圖交互變化(input) 觸發數據model變動的雙向綁定效果。app
class Mvvm{ constructor(options){ this.$options=options; this.data=this._data = this.$options.data; console.log(this.$options) var self = this; // 數據代理,實現響應,vue3會改寫,使用proxy代理方式 Object.keys(this.data).forEach(function(key) { self.defineReactive(key); }); this.initComputed(); new Observer(this.data, this); this.$compile = new Compile(this.$options.el || document.body, this) } defineReactive(key){ var self=this; Object.defineProperty(this,key,{ configurable:false, enuselfrable:true, get(){ return self.data[key]; }, set(newValue){ self.data[key]=newValue; } }) } }
基本上就大功告成了,大部分代碼都是參考了vue源碼的實現,學着讀源碼吧,體會vue設計的優雅。順便推薦一個github讀源碼的chrome插件:octotree.本文完整代碼請查看github mvvm
本文同步發表於我的博客函數
順便說一句,最近開始找工做了,座標北京,若是各位大佬有機會,望推薦下哈,在此先行謝過!源碼分析