proxy的深度拦截实现

   let obj = {
        city: "北京",
        area: ['海淀区', '石景山区', '门头沟区'],
        children: {
            test1: {
                name: "鲁谷",
                area: ['sss', 'bbb']
            }
        }
    };

    /**
     *      深层处理
     *
     */

    function prox(obj) {
        return new Proxy(obj, {
            get(target, p, receiver) {
                console.log(target, p, receiver);
                return target[p]
            },
            set(target, p, value, receiver) {
                console.log(value);
                target[p] = value;
                return true
            }
        });
    };

    function MyProxy(Obj) {
        // 深度遍历
        if (typeof Obj === 'object') {
            const status = Array.isArray(Obj);
            if (status) {
                Obj.forEach((v,i) => {
                    if (typeof v === 'object') {
                        Obj[i] = MyProxy(v)
                    }
                })
            } else  {

                Object.keys(Obj).forEach(v => {
                     if (typeof Obj[v] === 'object') {
                         Obj[v] = MyProxy(Obj[v])
                     }
                });
            }
            const Vue = prox(Obj); // 数据代理
            return Vue
        }
        return new TypeError("Argument must be object or array");
    }

    let Vue = MyProxy(obj);
    console.log(Vue.children.test1.name);
    Vue.children.test1.name = "永定河"

版权声明:本文为weixin_40629549原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。