Vue3的ref和reactive

158 阅读1分钟
  • reactive干嘛的?

给一个复杂对象响应化

  • ref干嘛的?

既可以给基本类型响应化,也可以给一个复杂对象响应化

  • 区别呢?

直接看源码:

github.com/vuejs/core/…

// ref api实现
export function ref(value?: unknown) {
  return createRef(value, false)
}

function createRef(rawValue: unknown, shallow: boolean) {
  if (isRef(rawValue)) {
    return rawValue
  }
  return new RefImpl(rawValue, shallow)
}

class RefImpl<T> {
  private _value: T
  private _rawValue: T

  public dep?: Dep = undefined
  public readonly __v_isRef = true

  constructor(value: T, public readonly __v_isShallow: boolean) {
    this._rawValue = __v_isShallow ? value : toRaw(value) 
    this._value = __v_isShallow ? value : toReactive(value)
  }

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

  set value(newVal) {
    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)
    }
  }

注意其中的

this._value = __v_isShallow ? value : toReactive(value)

意思就是:

1、当传进去的值是基本类型,.value进行赋值

2、当传进去的值是复杂类型,调用的reactive对值进行处理,赋值进value

3、后面的get及set进行响应监听及处理

所以,当ref(复杂类型)时,原理还是用的reactive,ref只是对其进行了一层包装而已

一句话概括:只要不嫌弃.value写法,ref吃遍天下