[Vue]Vue3 中的 ref 和 reactive 有什么区别

发布时间:2022-07-02 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了[Vue]Vue3 中的 ref 和 reactive 有什么区别脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

先来看看 ref 创建的数据和 reactive 创建的数据返回的类型是什么

console.LOG(ref({value: 0})) // => RefImpl
console.log(reactive({value: 0}) // => Proxy

ref 返回的是 RefImpl,而 ref 的 RefImpl._value(可以通过控制台打印查看到RefImpl内的_value)是一个 reactive 代理的原始对象;reactive 返回就是一个 PRoxy 了。这是为什么?让我们来剖析码:

在 reactivITy 文件夹中,找到一个文件 reactivity.xxx.js,第 963 行开始

在我们使用 ref 函数创建一个响应式数据时,ref 会调用 createRef 函数来创建一个 RefImpl 对象:

function ref(value) {
    return createRef(value, false);
}

function createRef(rawValue, shallow) {
    if (isRef(rawValue)) {
        return rawValue;
    }
    return new RefImpl(rawValue, shallow);
}

createRef 接收的 rawValue 如果已经是一个 RefImpl 对象了,也就是其属性 __v_isRef 为 true,就不再创建新的 RefImpl 对象,而是直接返回 rawValue。

否则,会创建一个 RefImpl 对象。

// RefImpl 类
class RefImpl {
    constructor(value, _shallow) {
        this._shallow = _shallow;
        this.dep = undefined;
        this.__v_isRef = true;
        this._rawValue = _shallow ? value : toRaw(value);
        this._value = _shallow ? value : toReactive(value);
    }


    get value() {
        trackRefValue(this);
        return this._value;
    }

    set value(newVal) {
        newVal = this._shallow ? newVal : toRaw(newVal);
        if (hasChanged(newVal, this._rawValue)) {
            this._rawValue = newVal;
            this._value = this._shallow ? newVal : toReactive(newVal);
            triggerRefValue(this, newVal);
        }
    }
}

凡是一个 ref 对象都应当有 __v_isRef 属性,且为 true,它用于 createRef 函数判断其是否为 RefImpl。

实际上 ref 仍然调用的是 reactive 函数,也就是 RefImpl 对象中 _value 通过 toReactive 获取 reactive 返回的代理对象。

const toReactive = (value) => shared.isObject(value) ? reactive(value) : value;

总结:我们使用 ref 其实就是使用的 reactive,两者仅在写法上存在差异,ref 必须通过 getter/setter 来访问或修改属性,而 reactive 可以通过属性访问表达式来访问或修改属性。

脚本宝典总结

以上是脚本宝典为你收集整理的[Vue]Vue3 中的 ref 和 reactive 有什么区别全部内容,希望文章能够帮你解决[Vue]Vue3 中的 ref 和 reactive 有什么区别所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。