学习vue3 proxy

vue3的数据响应用了proxy的方式,所有特来实验一下下。

let Watcher=function (obj,setFunc,getFunc) {
        let handler={
            get(target,property,receiver){
                let val=Reflect.get(target, property, receiver);
                getFunc(property,val);
                if(typeof val==='object'){
                    return Watcher(val,setFunc,getFunc);
                }else{
                    return val
                }
            },
            set(target,property,value,receiver){
                let old=Reflect.get(target, property, receiver);
                if(!Reflect.has(target,property)||old!==value){
                    setFunc(property,value,old);
                }
                return Reflect.set(target, property, value,receiver)
            }
        };
        return new Proxy(obj,handler)
    };
    let person=Watcher({name:'张三',hobby:{cheese:true}},function (key,newVal,oldVal) {
        console.log(key,newVal,oldVal)
    },function (key,val) {
        console.log(key,val)
    });
    // person.name='李四';
    //person.hobby.cheese=false;
    // console.log(person.hobby)
    // person.age=23;

你可能感兴趣的:(学习vue3 proxy)