html:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 6 <title>Document</title> 7 </head> 8 <body> 9 <div id="app"> 10 11 </div> 12 <script src="./vue.js"></script> 13 <script> 14 var vm = new Vue(); 15 setTimeout(()=>{ 16 vm.$data.a = 123 17 },4000) 18 </script> 19 </body> 20 </html>
js:
1 function Vue(){ 2 this.$data = {a:1}, 3 this.el = document.getElementById('app'); 4 this.virtualDom =''; 5 this.observe(this.$data); 6 this.render(); 7 } 8 //数据劫持 ,数据监听 9 Vue.prototype.observe = function(obj){ 10 var _self = this; 11 var _value; 12 for(var key in obj){ 13 _value = obj[key] 14 if(typeof _value == 'object'){ 15 _self.observe(_value) 16 }else{ 17 Object.defineProperty(obj,key,{ 18 get:function(){ 19 //依赖收集 20 return _value 21 }, 22 set:function(newValue){ 23 //触发视图更新 24 _value = newValue 25 _self.render(); 26 } 27 }) 28 } 29 } 30 } 31 Vue.prototype.render = function(){ 32 // 读取视图模板,生成 AST 语法树 33 this.virtualDom ='I am '+ this.$data.a; 34 //重新渲染、更新视图 35 this.el.innerHTML = this.virtualDom 36 }