shallowRef

Only the underlying data type responsivity is handled, not the object type responsivity.

// It can handle this
const count = shallRef(0);

// This is not the case
const obj = shallRef({name:"Mr.long"})
Copy the code

Why does shallowRef only handle responses of underlying data types

We know that if we pass an object to ref, the underlying function is called reactive by default. The return is a RefImpl object. Look at the source code.

class RefImpl<T> {
  private _rawValue: T

  private _value: T

  public readonly __v_isRef = true
   // If _shallow is true then toRaw and convert are not called
  constructor(value: T, public readonly _shallow = false) {
    // toRaw gets the original value of value
    this._rawValue = _shallow ? value : toRaw(value)
    // If an object is passed in, reactive is used by default
    this._value = _shallow ? value : convert(value)
  }

  get value() {
    track(toRaw(this), TrackOpTypes.GET, 'value')
    return this._value
  }

  set value(newVal) {
    // newVal gets a non-responsive value...
    newVal = this._shallow ? newVal : toRaw(newVal)
    // Determine whether the value passed in has changed
    if (hasChanged(newVal, this._rawValue)) {
      this._rawValue = newVal
      this._value = this._shallow ? newVal : convert(newVal)

      trigger(toRaw(this), TriggerOpTypes.SET, 'value', newVal)
    }
  }
}
Copy the code

The constructor function of the RefImpl class makes a judgment that if _shallow is true then the toRaw and convert functions are not called and the original values are returned. So the shallowRef function is called with the second argument true.

shallReactive

Only responsive data from the outermost layer of the object is processed (shallow responsive)

const obj = reactive({name:"Mr.long".son: {name:"Mr.liu"}})
// Vue will not do son.name
Copy the code