vue的原理解析
可以从下图中看出
1、通过建立虚拟dom树document.createDocumentFragment(),方法创建虚拟dom树。
2、一旦被监测的数据改变,会通过Object.defineProperty定义的数据拦截,截取到数据的变化。
3、截取到的数据变化,从而通过订阅——发布者模式,触发Watcher(观察者),从而改变虚拟dom的中的具体数据。
4、最后,通过更新虚拟dom的元素值,从而改变最后渲染dom树的值,完成双向绑定
最后附上全部代码,简单实现了一下,可在线直接运行编辑
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>BFWJS DEMO PAGE</title> </head> <body> <div id="mvvm"> <span>{{text}}</span> <input v-model="d" id="test" /> <input type='button' v-click="go" value="提交" /> <div> </div> </div> <script type="text/javascript"> var obj = {}; function nodeContainer(node, vm, flag) { var flag = flag || document.createDocumentFragment(); var child; while (child = node.firstChild) { compile(child, vm); flag.appendChild(child); if (child.firstChild) { nodeContainer(child, vm, flag); } } return flag; } //编译 function compile(node, vm) { var reg = /\{\{(.*)\}\}/g; if (node.nodeType === 1) { var attr = node.attributes; //解析节点的属性 for (var i = 0; i < attr.length; i++) { if (attr[i].nodeName == 'v-model') { var name = attr[i].nodeValue; node.addEventListener('input', function(e) { vm[name] = e.target.value; }); node.value = vm[name]; //讲实例中的data数据赋值给节点 node.removeAttribute('v-model'); } if (attr[i].nodeName == 'v-click') { var name = attr[i].nodeValue; node.addEventListener('click', function(e) { vm[name](); }); node.removeAttribute('v-click'); } } } //如果节点类型为text if (node.nodeType === 3) { if (reg.test(node.nodeValue)) { // console.dir(node); var name = RegExp.$1; //获取匹配到的字符串 name = name.trim(); // node.nodeValue = vm[name]; new Watcher(vm, node, name); } } } function defineReactive (obj, key, value) { var dep = new Dep(); Object.defineProperty(obj, key, { get: function() { console.log(Dep.global); if (Dep.global) { dep.add(Dep.global); } console.log("get了值"+value); return value; }, set: function(newValue) { if (newValue === value) { return; } value = newValue; console.log("set了最新值"+value); dep.notify(); } }) } function observe (obj, vm) { Object.keys(obj).forEach(function(key) { defineReactive(vm, key, obj[key]); }) } function Vue(options) { this.data = options.data; var data = this.data; observe(data, this); var id = options.el; var dom = nodeContainer(document.getElementById(id), this); document.getElementById(id).appendChild(dom); } function Dep() { this.subs = []; } Dep.prototype = { add: function(sub) { this.subs.push(sub); }, notify: function() { this.subs.forEach(function(sub) { console.log(sub); sub.update(); }) } } function Watcher(vm, node, name) { Dep.global = this; this.name = name; this.node = node; this.vm = vm; this.update(); Dep.global = null; } Watcher.prototype = { update: function() { this.get(); switch (this.node.nodeType) { case 1: this.node.value = this.value; break; case 3: this.node.nodeValue = this.value; break; default: break; } }, get: function() { this.value = this.vm[this.name]; } } var Demo = new Vue({ el: 'mvvm', data: { text: 'HelloWorld', d: '123', go: function() { alert(this.d); } } }) </script> </body> </html>
网友评论0