vue2.x和vue3的数据响应式原理有什么差异?

vue2.x用的核心函数是Object.defineProperty,只能监听一个属性,所以要想监听一个对象,需要用到for in 处理

function Vue(){
    //选项写死,便于演示
    this.$data = {
        a:1
    };
    this.el = document.getElementById('app');
    this._html = '';
    this.observe(this.$data);
    this.render();
}
Vue.prototype.observe= function(obj){
    var value;
    var that = this;
    for(var key in obj){
        value = obj[key];
        if(typeof value === 'object'){
            this.observe(value);
        }else{
            Object.defineProperty(this.$data,key,{
                get:function(){
                    return value
                },
                set:function(newValue){
                    value = newValue;
                    self.render();
                }
            })
        }
    }
}
Vue.prototype.render = function(){
    // 这里实际复杂的多节,解析模板(template),虚拟dom 转真实dom
    this._html = this.$data.a;
    this.el.innerHTML = this._html;
}
// 只要this.$data改变就会触发试图更新
 
 
var $vm = new Vue();
setTimeout(()=>{
   $vm.$data.a = 1000; //模拟数据更改
},2000)

而vue3用proxy写,proxy可以监听整个对象。省去for in提升效率,并且可以监听数组,不用再去单独的对数组做特异性操作

function Vue(){
    this.$data = {
        a:1
    };
    this.el = document.getElementById('app');
    this._html = '';
    this.observe(this.$data);
    this.render();
}
Vue.prototype.observe= function(obj){
    var value;
    var that = this;
    // 用proxy就不需要for in了,即监听的颗粒度减小了,拿到的信息更多了。
    this.$data = new Proxy(obj,{
        get:function(target,key,reveive){
            return target[key];// 不需要中间变量了
        },
        set: function (target, key, newValue,reveive){
            target[key] = newValue;
        }
    })
}
Vue.prototype.render = function(){
    // 这里实际复杂的多节,解析模板(template),虚拟dom 转真实dom
    this._html = this.$data.a;
    this.el.innerHTML = this._html;
}
// 只要this.$data改变就会触发试图更新
 
 
var $vm = new Vue();
setTimeout(() => {
    $vm.$data.a = 1000; //模拟数据更改
}, 2000)

原文链接:https://blog.csdn.net/ChasenZh/java/article/details/102760184

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容