vue3 手写组合API
// 手写组合API // 1. 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 } // 2. shallowReadonly 和 readonly const readonlyHandler = { get (target, prop) { console.log('只读 get......', prop) return Reflect.get(target, prop) }, set (target, prop, value) { console.error('只读不允许修改 set........') return true }, deleteProperty (target, prop) { console.error('只读不允许删除 deleteProperty........') return true } } const shallowReadonly = (target) => { if (target && typeof target === 'object') { return new Proxy(target, readonlyHandler) } return target } const readonly = (target) => { if (target && typeof target === 'object') { for (let k in target) { if (target.hasOwnProperty(k)) { target[k] = shallowReadonly(target[k]) } } return new Proxy(target, readonlyHandler) } return target } // 3. shallowRef 和 ref const shallowRef = (target) => { return { _value: target, get value () { console.log('进入数据劫持 get.........') return this._value }, set value (newValue) { console.log('进入数据劫持 set.........', newValue) this._value = newValue } } } const ref = (target) => { target = reactive(target) return { _value: target, get value () { console.log('进入数据劫持 get.........') return this._value }, set value (newValue) { console.log('进入数据劫持 set.........', newValue) this._value = newValue } } } // 新增内置组件 // 1. Fragement // 2. Teleport: 包裹的内容插入到 body <Teleport to="body"> <div>ssssss</div> </Teleport> // 3. Suspense: 异步组价加载中的渲染 <Suspense> <template #default> <组件 /> </template> <template v-slot:fallback> <Loading /> </tempalte> </Suspense>