手写组合API-shallowReactive 和 reactive

// shallowReactive 和 reactive
const reactiveHandler = {
    get(target, prop) {
        console.log('拦截器 get..........', prop)
        return Reflect.get(target, prop)
    },
    set(target, prop, value) {
        console.log('拦截器 set..........', prop, value)
        return Reflect.set(target, prop, value)
    },
    deleteProperty (target, prop) {
        console.log('拦截器 deleteProperty..........', prop)
        return Reflect.deleteProperty(target, prop)
    }
}
const shallowReactive = (target) => {
    if (target && typeof target === 'object') {
        return new Proxy(target, reactiveHandler)
    }
    return target
}

const reactive = (target) => {
    if (target && typeof target === 'object') {
        if (Array.isArray(target)) {
            target.forEach((item, index) => {
                target[index] = reactive(item)
            })
        } else {
            Object.keys(target).forEach(k => {
                target[k] = reactive(target[k])
            })
        }
        return new Proxy(target, reactiveHandler)
    }
    return target
}
const reactive = (target) => {
    if (target && typeof target === 'object') {
        for (let k in target) {
            if (target.hasOwnProperty(k)) {
                target[k] = reactive(target[k])
            }
        }
        return new Proxy(target, reactiveHandler)
    }
    return target
}

 

posted @ 2022-08-29 17:36  monkey-K  阅读(22)  评论(0编辑  收藏  举报