Vue 大行其道,但其实现原理到底是怎样的呢。想要彻底说清楚,恐怕一两顿饭的时间是不够的。但是可以通过简单的实现方式,能够明白其大概思路。
实现代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| class Vue{ constructor(opt){ this.opt = opt this.observe(opt.data) let root = document.querySelector(opt.el) this.compile(root) } observe(data){ Object.keys(data).forEach(key => { let obv = new Observer() data["_"+key] = data[key] Object.defineProperty(data, key, { get(){ Observer.target && obv.addSubNode(Observer.target); return data['_'+key] }, set(newVal){ obv.update(newVal) data['_'+key] = newVal } }) }) } compile(node){ [].forEach.call(node.childNodes, child =>{ if(!child.firstElementChild && /\{\{(.*)\}\}/.test(child.innerHTML)){ let key = RegExp.$1.trim() child.innerHTML = child.innerHTML.replace(new RegExp('\\{\\{\\s*'+ key +'\\s*\\}\\}', 'gm'),this.opt.data[key]) Observer.target = child this.opt.data[key] Observer.target = null } else if (child.firstElementChild) this.compile(child) }) } }
class Observer{ constructor(){ this.subNode = [] } addSubNode(node){ this.subNode.push(node) } update(newVal){ this.subNode.forEach(node=>{ node.innerHTML = newVal }) } }
|
demo示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <div id='app'> <h3>姓名</h3> <p>{{name}}</p> <h3>年龄</h3> <p>{{age}}</p> </div> </body> </html> <script> document.addEventListener('DOMContentLoaded', function(){ let opt = {el:'#app', data:{name:'检索中...', age:30}} let vm = new Vue(opt) setTimeout(() => { opt.data.name = '王永峰' }, 2000); }, false)
</script>
|