data changes responsive vue

data changes responsive vue

Man of few words said, the first on the code:

//拷贝一份数组原型,防止修改所有数组类型变量的原型方法
let arrayProto = Array.prototype;// 数组原型上的方法
let proto = Object.create(arrayProto);
//重写以下几个方法
['splice','unshift','push','sort','reserve','shift','pop'].forEach(method=>{
    proto[method] = function(...args){
        let inserted;//默认没有插入新数据
        switch(method){
            case 'push':
            case 'unshift':
                inserted = args;//参数是数组
                break;
            case 'splice':
                inserted = args.slice(2);//splice方法参数大于等于三个才是添加
            default:
                break;
        }
        observeArray(inserted);
        console.log('视图更新');
        // Array.prototype.push.call([1,2,3],4,5,6);
        arrayProto[method].call(this,...args);
    }
});
//监控数组
function observeArray (obj){
    for(let i = 0; i<obj.length;i++){
            observe(obj[i])//数组中普通值不会被监控,对象会被监控
        }
}
//监控
function observe (obj){
    //基本数据类型直接返回不需要监控
    if((typeof obj !== 'object'&& typeof obj !== 'function') || obj == null){
        return obj
    }
    //数组的处理方式
    if(Array.isArray(obj)){
        //重写该数组原型的方法
        Object.setPrototypeOf(obj,proto);
        observeArray(obj);
    }else{//对象的处理方式
        for(let key in obj){
            defineReactive(obj,key,obj[key])
        }
    }
}
//调用Object.defineProperty()方法,监控数据
function defineReactive(obj,key,value){
    observe(value);//递归监控数据
    Object.defineProperty(obj,key,{
        get(){
            return value;
        },
        set(newValue){
            if(value!==newValue){
                observe(newValue);
                value = newValue;
            }
        }
    })
}
let data = {
    name:'yh',
    arr:[1,2,3]
}
observe(data);
data.arr = [1,2];//更新
data.arr.push(996);//更新
data.arr[3] = 251;//不更新

Logical steps:
1, mass participation data, determines the type of data
2.1, if it is returned directly to the basic type
2.2, if the array is an array of the method of the seven loop array and rewriting the data as children traversed again down a first step
2.3 if the object or function, then add to the cycle monitoring, and children take the first step as the data again

Features: Use when the object must be declared attribute, which is the type of response
1. there is no increase in the property can not update the view ($ vm the SET.)
2. default recursion increase getter and setter
3. Object array sets of objects support is responsive change is a constant if there is no effect
4. modify the array index and length will not cause updated view
5. If the new data will help you to monitor the vue (object type)

Guess you like

Origin www.cnblogs.com/yhbh/p/11995874.html