首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >vue2、vue3双向数据绑定对比

vue2、vue3双向数据绑定对比

作者头像
用户3258338
发布2019-10-23 18:36:01
7760
发布2019-10-23 18:36:01
举报

html文件:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <div id="app"></div>
  <script type="text/javascript" src='./index.js'></script>
</body>
</html>

vue2 的index.js

function vue (){
  this.$data = {
    a:1,
    b : 2  }
  this.el = document.getElementById('app');
  this.html = '';  this.observe(this.$data);
  this.render();
}
// 监听obj的变化vue.prototype.observe = function(obj){
  for(var key in obj){
    var value = obj[key];
    var self = this;
    if(typeof value === "object"){
      this.observe(value)
    }else{      
      // 重新定义了obj的set和get方法
      Object.defineProperty(obj,key,{
        get:function(){
          return value;
        },
        set:function(newVal){ 
         value = newVal;
          self.render();
        }
      })
    }
  }
}
// 渲染dom
vue.prototype.render =function(){
  this.html = this.$data.a;
  this.el.innerHTML = this.html;
}
var vueObj = new vue();

setTimeout(function(){
  vueObj.$data.a = 89
},5000)

可以看到开始时候浏览器:

5秒之后:

vue3的index.js文件:

function vue (){
  this.$data = {
      a:1,
      b : 2
  }
  this.el = document.getElementById('app');
  this.html = '';  this.observe(this.$data);
  this.render();
}
// 监听obj的变化
vue.prototype.observe = function(obj){

    for(var key in obj){
       var value = obj[key];
       var self = this;
       if(typeof value === "object"){
         this.observe(value)
       }else{      
          // 重新定义了obj的set和get方法
          this.$data = new Proxy(obj,{
             get: function(obj, name){
             return obj[name] ;
           },        
           set: function(obj,name,newVal){          
             obj[name] = newVal;          
             self.render();
        }
      })
    }
  }
}
// 渲染dom
vue.prototype.render =function(){
  this.html = this.$data.a;
  this.el.innerHTML = this.html;
}

var vueObj = new vue();

setTimeout(function(){

  vueObj.$data.a = 89
},4000)

如果宝宝们细看,vue2和vue3的数据绑定部分,实际上重要的将defineproperty换成了Proxy。

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-10-16,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 女程序员的日常 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档