实现一个最小版本vue(五)之watcher

watcher

功能

  • 数据发生变化触发依赖,dep通知所有watcher更新视图

  • 自身实例化的时候往dep对象中添加自己

  • 结构

实现思路

data中每个属性,都会创建一个dep对象,dep收集依赖时,把所有依赖该属性的观察者添加到dep里的subs数组里,setter里触发依赖,调用dep的notify,通知所有关联的watcher,watcher负责更新视图

代码

class Watcher {
  constructor (vm, key, cb) {
    this.vm = vm
    // data中的属性名称
    this.key = key
    // callback更新视图
    this.cb = cb
    // 当前watcher对象记录到dep的target静态属性中
    Dep.target = this
    // vm[key]这里,先触发vue里的getter,vue里的getter触发observer的get方法,get方法里会调用addSub,把当前Watcher对象添加到dep
    this.oldValue = vm[key]
    // 重置,防止重复添加
    Dep.target = null
  }

  // 当数据变化时,更新视图
  update () {
    // 先获取最新的
    let newValue = this.vm[this.key]
    if (this.oldValue === newValue) {
      return
    }
    // 如果不等,调用cb进行更新
    this.cb(newValue)
  }
}
posted @ 2020-07-08 16:46  Evo1uti0n  阅读(177)  评论(0编辑  收藏  举报