手撸vue3核心源码——响应式原理(shallowReadonly, isProxy)

简介: 手撸vue3核心源码——响应式原理(shallowReadonly, isProxy)

shallowReadonly

shallowReadonly也就是只对最外层做readonly,内部如果还要对象属性,不做readonly处理

那么我们如果是shallow的话,就不用递归了,借鉴isReaonly写法,我们也传入一个变量用于检验是否是shallow

image.png

编辑

这是我们写的单测, 最下面两行是实现的功能


function createGetter(isReadonly = false, isShallow = false) {
    return function get(target, key) {
        if (key === reactiveFlags.IS_REACTIVE) {
            return !isReadonly
        } else if (key === reactiveFlags.IS_READONLY) {
            return isReadonly
        }
        const res = Reflect.get(target, key)
        if (isShallow) {
            return res
        }
        if (isObject(res)) {
            return isReadonly ? readonly(res) : reactive(res)
        }
        if (!isReadonly) {
            track(target, key)
        }
        return res
    }
}

我们知道readonly与reactive区别是readonly不做依赖收集,而shallow与readonly区别是,我们不需要再递归了,因此,我们传入一个shallow变量,当为true的时候直接返回res即可,不需要再递归将深层的对象属性也变成readonly

这样我们再创建一个shallowReadonly的方法来让它的get方法变成这样即可


const getShallowReadonly = createGetter(true, true)
export const readonlyHandler = {
    get: getReadonly,
    set(target, key, value) {
        console.warn(`${key}不能set 因为target 是readonly`, target)
        return true
    }
}
export const shallowReaonlyHandler = extend({}, readonlyHandler,
    { get: getShallowReadonly }
)

这里的extend方法是Object.assign,因为shallowReadonly与readonly的set方法一样,因此不要再写一遍set方法了


isProxy

image.png

image.png


是否是一个Proxy对象,这个很简单就可以实现,只需要判断它是否是一个reactive或者一个readonly即可

以下是readonly以及reactive要实现的单元测试

export function isProxy(value) {
    return isReactive(value) || isReadonly(value)
}

我们直接调用isReactive与isReadonly即可,如果是其中之一那就是proxy,如果不是那就不是Proxy

相关文章
|
3天前
|
JavaScript 前端开发 CDN
vue3速览
vue3速览
12 0
|
3天前
|
设计模式 JavaScript 前端开发
Vue3报错Property “xxx“ was accessed during render but is not defined on instance
Vue3报错Property “xxx“ was accessed during render but is not defined on instance
|
3天前
|
JavaScript API
Vue3 官方文档速通(中)
Vue3 官方文档速通(中)
18 0
|
3天前
|
缓存 JavaScript 前端开发
Vue3 官方文档速通(上)
Vue3 官方文档速通(上)
20 0
|
3天前
Vue3+Vite+Pinia+Naive后台管理系统搭建之五:Pinia 状态管理
Vue3+Vite+Pinia+Naive后台管理系统搭建之五:Pinia 状态管理
8 1
|
3天前
Vue3+Vite+Pinia+Naive后台管理系统搭建之三:vue-router 的安装和使用
Vue3+Vite+Pinia+Naive后台管理系统搭建之三:vue-router 的安装和使用
7 0
|
3天前
Vue3+Vite+Pinia+Naive后台管理系统搭建之二:scss 的安装和使用
Vue3+Vite+Pinia+Naive后台管理系统搭建之二:scss 的安装和使用
6 0
|
3天前
|
JavaScript 前端开发 API
Vue3 系列:从0开始学习vue3.0
Vue3 系列:从0开始学习vue3.0
9 1
|
3天前
|
网络架构
Vue3 系列:vue-router
Vue3 系列:vue-router
8 2
|
3天前
Vue3+Vite+Pinia+Naive后台管理系统搭建之一:基础项目构建
Vue3+Vite+Pinia+Naive后台管理系统搭建之一:基础项目构建
7 1