vue2的响应式依赖defineProperty,实例化组件时,对props、computed、data、methods做数据劫持处理,同时为组件this实例做数据访问代理,比如:

  1. export function proxy (
  2. target: Object, sourceKey: string, key: string
  3. ) {
  4. // desc
  5. sharedPropertyDefinition.get = function proxyGetter () {
  6. return this[sourceKey][key]
  7. }
  8. /*
  9. sourceKey就是methods、data,props,
  10. 定义时proxy(vm, `_props`, key), vm就是组件实例
  11. key就是具体的对象字段
  12. */
  13. sharedPropertyDefinition.set = function proxySetter (val) {
  14. this[sourceKey][key] = val
  15. }
  16. Object.defineProperty(target, key, sharedPropertyDefinition)
  17. }

有了这层代理,所以在组件中才能从this对象上获取组件内外所有属性

数据劫持

对于设置获取属性时,vue通过definePropertyapi做拦截,做到对数据的劫持,也就是描述符中get(), set() 方法。 比如

Object.defineProperty(target, key, {
  get() {
    // 在获取, 此时收集key-value的依赖
    return sourceValue;
  },
  set(newVal) {
    sourceValue = newVal;
    // 重新设置,同时key-value的依赖项开始更新
  }
});
function defineReactive (
  obj: Object,
  key: string,
  val: any,
  customSetter?: ?Function,
  shallow?: boolean
) {
   // 对于key的依赖项, 也就是一个key对对应一个dep
  // dep会收集watcher
  const dep = new Dep()

  // 获取当前属性的描述符, 所以对于不需要响应式的对象
  // 可以设置为不可配置的
  const property = Object.getOwnPropertyDescriptor(obj, key)
  if (property && property.configurable === false) {
    return
  }

  // 兼容自定义的getter、setter
  const getter = property && property.get
  const setter = property && property.set
  if ((!getter || setter) && arguments.length === 2) {
    val = obj[key]
  }
  // 每次会递归的处理,所有对象都是可控的
  let childOb = !shallow && observe(val)

  Object.defineProperty(obj, key, {
    enumerable: true,
    configurable: true,
    get: function reactiveGetter () {
      const value = getter ? getter.call(obj) : val
      if (Dep.target) {
        // 依赖收集, dep和warcher的双向绑定,彼此都会存在于依赖项中
        dep.depend()
        if (childOb) {
          // 子元素的依赖
          childOb.dep.depend()
          if (Array.isArray(value)) {
            // ?懂
            dependArray(value)
          }
        }
      }
      return value
    },
    set: function reactiveSetter (newVal) {
      const value = getter ? getter.call(obj) : val
      /* eslint-disable no-self-compare */
      if (newVal === value || (newVal !== newVal && value !== value)) {
        return
      }
      /* eslint-enable no-self-compare */
      if (process.env.NODE_ENV !== 'production' && customSetter) {
        customSetter()
      }
      // #7981: for accessor properties without setter
      if (getter && !setter) return
      if (setter) {
        setter.call(obj, newVal)
      } else {
        val = newVal
      }
      // 对新赋值的value做观测
      childOb = !shallow && observe(newVal)
       // value已经更新,通知依赖项
      dep.notify()
    }
  })
}

观察者

warcher为vue和响应式实现中一个连接点,一个组件在被实例化时会被创建一个watcher, 组件的后续更新会有watcher管理,在更新时也会调用vue中的更新函数,也会间接出发生命周期函数,比如before\update


export default class Watcher {
  vm: Component;
  expression: string;
  cb: Function;
  id: number;
  deep: boolean;
  user: boolean;
  lazy: boolean;
  sync: boolean;
  dirty: boolean;
  active: boolean;
  deps: Array<Dep>;
  newDeps: Array<Dep>;
  depIds: SimpleSet;
  newDepIds: SimpleSet;
  before: ?Function;
  getter: Function;
  value: any;

  constructor (
    vm: Component,
    expOrFn: string | Function,
    cb: Function,
    options?: ?Object,
    isRenderWatcher?: boolean
  ) {
    // 一个绑定组件的实例
    this.vm = vm
    if (isRenderWatcher) {
      vm._watcher = this
    }
    // 实例和watcher绑定,组件中的watch会有关联
    vm._watchers.push(this)
    // options
    if (options) {
      this.deep = !!options.deep
      this.user = !!options.user
      this.lazy = !!options.lazy
      this.sync = !!options.sync
      this.before = options.before
    } else {
      this.deep = this.user = this.lazy = this.sync = false
    }
    // 处理更新的毁掉
    this.cb = cb
    this.id = ++uid // uid for batching
    this.active = true
    this.dirty = this.lazy // for lazy watchers
    this.deps = []
    this.newDeps = []
    this.depIds = new Set()
    this.newDepIds = new Set()
    this.expression = process.env.NODE_ENV !== 'production'
      ? expOrFn.toString()
      : ''
    // parse expression for getter
    if (typeof expOrFn === 'function') {
      this.getter = expOrFn
    } else {
      this.getter = parsePath(expOrFn)
      if (!this.getter) {
        this.getter = noop
        process.env.NODE_ENV !== 'production' && warn(
          `Failed watching path: "${expOrFn}" ` +
          'Watcher only accepts simple dot-delimited paths. ' +
          'For full control, use a function instead.',
          vm
        )
      }
    }
    this.value = this.lazy
      ? undefined
      : this.get()
  }

  /**
   * 组件获取值时,会使用watcher的get方法获取,也就是收集依赖

   */
  get () {
    // 让全局变量Taget指向自己
    pushTarget(this)
    let value
    const vm = this.vm
    try {
      value = this.getter.call(vm, vm)
    } catch (e) {
      if (this.user) {
        handleError(e, vm, `getter for watcher "${this.expression}"`)
      } else {
        throw e
      }
    } finally {
      // "touch" every property so they are all tracked as
      // dependencies for deep watching
      if (this.deep) {
        traverse(value)
      }
      // 回滚
      popTarget()
      // 对于本次获取时产生不必要的副作用清空
      this.cleanupDeps()
    }
    // reutnr获取到的值
    return value
  }

  addDep (dep: Dep) {
    // 双向依赖
    // this中存在dep, dep中存在watcher
    const id = dep.id
    if (!this.newDepIds.has(id)) {
      this.newDepIds.add(id)
      this.newDeps.push(dep)
      if (!this.depIds.has(id)) {
        dep.addSub(this)
      }
    }
  }

  /**
   * Clean up for dependency collection.
   */
  cleanupDeps () {
    let i = this.deps.length
    while (i--) {
      const dep = this.deps[i]
      if (!this.newDepIds.has(dep.id)) {
        dep.removeSub(this)
      }
    }
    let tmp = this.depIds
    this.depIds = this.newDepIds
    this.newDepIds = tmp
    this.newDepIds.clear()
    tmp = this.deps
    this.deps = this.newDeps
    this.newDeps = tmp
    this.newDeps.length = 0
  }


  update () {
     // 更新,异步的更新

    if (this.lazy) {
      this.dirty = true
    } else if (this.sync) {
      this.run()
    } else {
      queueWatcher(this)
    }
  }

  run () {
    // 更新,使用get获取新值,(每次都会获取,所以要清空)
    // 获取到新值以后执行watch{}, 和updateComponent
    if (this.active) {
      const value = this.get()
      if (
        value !== this.value ||

        isObject(value) ||
        this.deep
      ) {
        // set new value
        const oldValue = this.value
        this.value = value
        if (this.user) {
          const info = `callback for watcher "${this.expression}"`
          invokeWithErrorHandling(this.cb, this.vm, [value, oldValue], this.vm, info)
        } else {
          this.cb.call(this.vm, value, oldValue)
        }
      }
    }
  } 
evaluate () {
    this.value = this.get()
    this.dirty = false
  }


  depend () {
    let i = this.deps.length
    while (i--) {
      // 让dep类和warcher绑定
      this.deps[i].depend()
    }
  }

  /**
   * 对于不必要的watcher移除
   */
  teardown () {
    if (this.active) {

      if (!this.vm._isBeingDestroyed) {
        remove(this.vm._watchers, this)
      }
      let i = this.deps.length
      while (i--) {
        // dep一样
        this.deps[i].removeSub(this)
      }
      this.active = false
    }
  }}

Dep


export default class Dep {
  static target: ?Watcher;
  id: number;
  subs: Array<Watcher>;

  constructor () {
    this.id = uid++
    this.subs = []
  }

  addSub (sub: Watcher) {
    this.subs.push(sub)
  }

  removeSub (sub: Watcher) {
    remove(this.subs, sub)
  }

  depend () {
    if (Dep.target) {
      Dep.target.addDep(this)
    }
  }

  notify () {
    // stabilize the subscriber list first
    const subs = this.subs.slice()
    if (process.env.NODE_ENV !== 'production' && !config.async) {
      // subs aren't sorted in scheduler if not running async
      // we need to sort them now to make sure they fire in correct
      // order
      subs.sort((a, b) => a.id - b.id)
    }
    for (let i = 0, l = subs.length; i < l; i++) {
      subs[i].update()
    }
  }
}
// 全局变量
Dep.target = null
const targetStack = []

export function pushTarget (target: ?Watcher) {
  targetStack.push(target)
  Dep.target = target
}

export function popTarget () {
  targetStack.pop()
  Dep.target = targetStack[targetStack.length - 1]
}

dep类负责在数据劫持中收集对当前活跃的key-value依赖的watcher,并在需要的时候通知他们(notify), 让watcher来处理本次更新, 继而更新组件

vue2中整个逻辑就是vue组件创建watcher, 在获取或设置新值时,被劫持到,由dep收集依赖,再回过头来通知watcehr来更新视图,watcher会调用vue中对组件存活期间对处理,比如mount、update时。