ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

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

2021-10-17 01:03:09  阅读:376  来源: 互联网

标签:RefImpl Vue newVal ._ value reactive Vue3 ref


区别

先来看看 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。我们看到 RefImpl 的 _value 是有一对 getter/setter 的,xx.value 实际上就是在调用 getter/setter。而 reactive 是通过属性访问表达式来访问或修改属性的。

标签:RefImpl,Vue,newVal,._,value,reactive,Vue3,ref
来源: https://www.cnblogs.com/shiramashiro/p/15415728.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有