← 返回首页
Vue3基础教程(三十六)
发表时间:2021-08-15 17:17:40
自定义shallowReadonly和readonly

1.自定义shallowReadonly与readonly

实例:

const readonlyHandler = {
    get (target, key) {
        if (key==='_is_readonly') return true
        return Reflect.get(target, key)
    },
    set () {
        console.warn('只读的, 不能修改')
        return true
    },
    deleteProperty () {
        console.warn('只读的, 不能删除')
        return true
    },
}

/*
自定义shallowReadonly
*/
function shallowReadonly(obj) {
    return new Proxy(obj, readonlyHandler)
}

/*
自定义readonly
*/
function readonly(target) {
    if (target && typeof target==='object') {
        if (target instanceof Array) { // 数组
            target.forEach((item, index) => {
                target[index] = readonly(item)
            })
        } else { // 对象
            Object.keys(target).forEach(key => {
                target[key] = readonly(target[key])
            })
        }
        const proxy = new Proxy(target, readonlyHandler)
        return proxy
    }
    return target
}

/* 测试自定义readonly */
/* 测试自定义shallowReadonly */
const obj1 = readonly({
    a: {
        b: 1
    }
})
const obj2 = shallowReadonly({
    a: {
        b: 1
    }
})

console.log(obj1);
obj1.a = 1
obj1.a.b = 2
console.log(obj1);

console.log(obj2);
obj2.a = 1
obj2.a.b = 2
console.log(obj2);