鍍金池/ 問答/HTML/ vuejs源碼關(guān)于observer部分的dep有什么作用

vuejs源碼關(guān)于observer部分的dep有什么作用

observer類:

constructor (value: any) {
    this.value = value
    this.dep = new Dep()
    this.vmCount = 0
    def(value, '__ob__', this)
    if (Array.isArray(value)) {
      const augment = hasProto
        ? protoAugment
        : copyAugment
      augment(value, arrayMethods, arrayKeys)
      this.observeArray(value)
    } else {
      this.walk(value)
    }
  }

這里的dep屬性有什么作用呢?
我知道defineReactive方法會改造getter setter方法來收集依賴和通知watcher,但是這個方法里都是用的閉包里的dep來操作的,為什么還要在observer里面聲明一個dep實例呢?

回答
編輯回答
別逞強

Dep是一個觀察者模式的class,初始化的時候?qū)atcher添加到sub數(shù)組中,數(shù)據(jù)改變時觸發(fā)Dep的notify,執(zhí)行Watcher,vue 更新view就是這樣做的

2017年9月17日 14:19
編輯回答
互擼娃

這個dep屬性是在Vue.$set和$delete中用到的。如$set中倒數(shù)第二行代碼

export function set (target: Array<any> | Object, key: any, val: any): any {
  if (process.env.NODE_ENV !== 'production' &&
    (isUndef(target) || isPrimitive(target))
  ) {
    warn(`Cannot set reactive property on undefined, null, or primitive value: ${(target: any)}`)
  }
  if (Array.isArray(target) && isValidArrayIndex(key)) {
    target.length = Math.max(target.length, key)
    target.splice(key, 1, val)
    return val
  }
  if (key in target && !(key in Object.prototype)) {
    target[key] = val
    return val
  }
  const ob = (target: any).__ob__
  if (target._isVue || (ob && ob.vmCount)) {
    process.env.NODE_ENV !== 'production' && warn(
      'Avoid adding reactive properties to a Vue instance or its root $data ' +
      'at runtime - declare it upfront in the data option.'
    )
    return val
  }
  if (!ob) {
    target[key] = val
    return val
  }
  defineReactive(ob.value, key, val)
  ob.dep.notify() // 這里的dep指的就是樓主所問的dep屬性
  return val
}
2017年3月12日 16:18