vue3解析

190 阅读1分钟

vue3解析

ref

ref(value) -> createRef(rawValue, shallow) -> isRef(rawValue)

- 是 return rawValue
- 否 new RefImp(rawValue, shallow)

creatRef

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

RefImpl

5个私有属性,1个value

dep: set 数据
__v_isRef: 是不是ref数据
__v_isShallow: 
_rawValue: 原数据,没有经过代理,劫持修改过的数据 toRaw(value)
_value:  toReactive(value)
value: setter getter
class RefImpl {
    constructor(value, __v_isShallow) {
        this.__v_isShallow = __v_isShallow;
        this.dep = undefined;
        this.__v_isRef = true;
        this._rawValue = __v_isShallow ? value : toRaw(value);
        this._value = __v_isShallow ? value : toReactive(value);
    }
    get value() {
        trackRefValue(this);
        return this._value;
    }
    set value(newVal) {
        debugger
        newVal = this.__v_isShallow ? newVal : toRaw(newVal);
        if (hasChanged(newVal, this._rawValue)) {
            this._rawValue = newVal;
            this._value = this.__v_isShallow ? newVal : toReactive(newVal);
            triggerRefValue(this, newVal);
        }
    }
}