vue的使用相信你们都很熟练了,使用起来简单。可是大部分人不知道其内部的原理是怎么样的,今天咱们就来一块儿实现一个简单的vuehtml
实现以前咱们得先看一下Object.defineProperty的实现,由于vue主要是经过数据劫持来实现的,经过get
、set
来完成数据的读取和更新。vue
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文档。node
<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>
new Vue({ el: '#wrap', data:{ form: '这是form的值', test: '<strong>我是粗体</strong>', }, methods:{ changeValue(){ console.log(this.form) this.form = '值被我改变了,气不气?' } } })
class Vue{ constructor(){} proxyData(){} observer(){} compile(){} compileText(){} } class Watcher{ constructor(){} update(){} }
Vue constructor
构造函数主要是数据的初始化proxyData
数据代理observer
劫持监听全部数据compile
解析domcompileText
解析dom
里处理纯双花括号的操做Watcher
更新视图操做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 } }
上面主要是初始化操做,针对传过来的数据进行处理git
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
github
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
里,等到时候须要更新的时候就能够批量更新数据了。👇下面就是;
遍历订阅池,批量更新视图。segmentfault
set(newValue){ if(newValue !== value){ value = newValue // 批量更新视图 that.watcherTask[key].forEach(task => { task.update() }) } }
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
里面,而后到时候在设置值的时候就能够批量更新了,实现双向数据绑定,也就是下面的操做dom
that.watcherTask[key].forEach(task => { task.update() })
而后push
的值是一个Watcher
的实例,首先他new的时候会先执行一次,执行的操做就是去把纯双花括号
-> 1,也就是说把咱们写好的模板数据更新到模板视图上。
最后把当前元素属性剔除出去,咱们用Vue
的时候也是看不到这种指令的,不剔除也不影响函数
至于Watcher
是什么,看下面就知道了this
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