Vue 2.5 数据绑定实现逻辑(一)整体逻辑

在概述中说到,Vue2.5的数据绑定主要是通过对象属性的 getter 和 setter 的钩子来实现的,总的来说是在初始化的时候建立起钩子,并且在数据更新的时候通知相应的 Watcher 去运行回调函数执行更新等操作。

具体来讲,要分以下几步:

  1. 初始化实例对象时运行initState, 建立好props, data 的钩子以及其对象成员的Observer, 对于computed 属性,则建立起所有对应的 Watcher 并且通过 Object.defineProperty 在vm对象上设置一个该属性的 getter。同时还根据自定义的 watch 来建立相应的 Watcher

  2. 执行挂载操作,在挂载时建立一个直接对应render(渲染)的 Watcher,并且编译模板生成 render 函数,执行vm._update 来更新 DOM 。

  3. 此后每当有数据改变,都将通知相应的 Watcher 执行回调函数。

而想要真正理解这里的逻辑, 则需要先搞清楚 Dep, Observer 和 Watcher 这三种对象的作用,以及定义的钩子函数中究竟做了什么。

Dep (dependency // 依赖)

位置: src/core/observer/dep.js

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()
    for (let i = 0, l = subs.length; i < l; i++) {
      subs[i].update()
    }
  }
}

Dep 就是一个 Watcher 所对应的数据依赖,在这个对象中也存有一个 subs 数组,用来保存和这个依赖有关的 Watcher。其成员函数最主要的是 depend 和 notify ,前者用来设置某个 Watcher 的依赖,后者则用来通知与这个依赖相关的 Watcher 来运行其回调函数。

另外还可以看到的是,这个类还有一个静态成员 target, 同时还有一个全局的栈,其中储存的是正在运行的Watcher。

Dep.target = null
const targetStack = []

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

export function popTarget () {
  Dep.target = targetStack.pop()
}

这里的压栈和出栈的方法就不用多说了。

Observer

位置: src/core/observer/index.js

class Observer {
  value: any;
  dep: Dep;
  vmCount: number; // number of vms that has this object as root $data

  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)
    }
  }

  /**
   * Walk through each property and convert them into
   * getter/setters. This method should only be called when
   * value type is Object.
   */
  walk (obj: Object) {
    const keys = Object.keys(obj)
    for (let i = 0; i < keys.length; i++) {
      defineReactive(obj, keys[i], obj[keys[i]])
    }
  }

  /**
   * Observe a list of Array items.
   */
  observeArray (items: Array<any>) {
    for (let i = 0, l = items.length; i < l; i++) {
      observe(items[i])
    }
  }
}

Observer 主要是用来监视一个对象的变化,比如在 data 中存在一个对象成员,直接给该对象成员添加属性并不会触发任何钩子函数,但是这个对象又是数据的一部分,也就是说该对象发生变化也会导致DOM发生改变,因此要用 Observer 来监视一个对象的变化并且在变化时通知与其相关的 Watcher 来运行回调函数。

可以看到,Observer 中存在一个 Dep,也就是一个依赖。

在建立 Observer 的时候会用到 observe 函数

export function observe (value: any, asRootData: ?boolean): Observer | void {
  if (!isObject(value) || value instanceof VNode) {
    return
  }
  let ob: Observer | void
  if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) {// 判断该对象是否已经存在 Observer
    ob = value.__ob__
  } else if (
    observerState.shouldConvert &&
    !isServerRendering() &&
    (Array.isArray(value) || isPlainObject(value)) &&
    Object.isExtensible(value) &&
    !value._isVue
  ) {
    ob = new Observer(value)
  }
  if (asRootData && ob) {
    ob.vmCount++
  }
  return ob
}

这个函数主要是用来动态返回一个 Observer,首先判断value如果不是对象则返回,然后检测该对象是否已经有 Observer,有则直接返回,否则新建并将 Observer 保存在该对象的 ob 属性中(在构造函数中进行)。

在建立 Observer 时,如果OB的是数组则对数组中每个成员执行 observe 函数,否则对每个对象属性执行 defineReactive 函数来设置 get set 钩子函数。

Watcher

位置: src/core/observer/watcher.js

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;
  getter: Function;
  value: any;

  constructor (
    vm: Component,
    expOrFn: string | Function,
    cb: Function,
    options?: ?Object,
    isRenderWatcher?: boolean
  ) {
    this.vm = vm
    if (isRenderWatcher) {
      vm._watcher = this
    }
    vm._watchers.push(this)
    // options
    if (options) {
      this.deep = !!options.deep
      this.user = !!options.user
      this.lazy = !!options.lazy
      this.sync = !!options.sync
    } 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 = function () {}
        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()
  }

  /**
   * Evaluate the getter, and re-collect dependencies.
   */
  get () {
    ......
  }

  /**
   * Add a dependency to this directive.
   */
  addDep (dep: Dep) {
    ......
  }

  /**
   * Clean up for dependency collection.
   */
  cleanupDeps () {
    ......
  }

  /**
   * Subscriber interface.
   * Will be called when a dependency changes.
   */
  update () {
    ......
  }

  /**
   * Scheduler job interface.
   * Will be called by the scheduler.
   */
  run () {
    ......
  }

  /**
   * Evaluate the value of the watcher.
   * This only gets called for lazy watchers.
   */
  evaluate () {
    ......
  }

  /**
   * Depend on all deps collected by this watcher.
   */
  depend () {
    ......
  }

  /**
   * Remove self from all dependencies' subscriber list.
   */
  teardown () {
    ......
  }
}

Watcher 在构造时传入的参数最重要的是 expOrFn , 这是一个 getter 函数,或者可以用来生成一个 getter 函数的字符串,而这个 getter 函数就是之前所说的回调函数之一另外一个回调函数是 this.cb,这个函数只有在用 vm.$watch 生成的 Watcher 才会运行。
getter 在 expOrFn 是字符串时,会运行 parsePath 取得其对应的在 Vue 实例对象上的一个熟悉。

其中 get 函数的职责就是执行 getter 函数并将可能的返回值(如果该 Watcher 是renderWatcher 则返回值是 undefined)赋值给该 Watcher 的 value 属性。

update 函数则是在一个 Dep 通过 notify 函数通知 Watcher 后执行的函数,在其中执行了 run 函数,run 中又执行了 get 函数。

depend 则是用来将 Watcher 中 deps 数组保存的所有依赖进行关联,使这些依赖在 notify 时可以通知到该 Watcher。

defineReactive

位置: src/core/observer/index.js

export function defineReactive (
  obj: Object,
  key: string,
  val: any,
  customSetter?: ?Function,
  shallow?: boolean
) {
  const dep = new Dep()

  const property = Object.getOwnPropertyDescriptor(obj, key)
  if (property && property.configurable === false) {
    return
  }

  // cater for pre-defined getter/setters
  const getter = property && property.get
  const setter = property && property.set

  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.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()
      }
      if (setter) {
        setter.call(obj, newVal)
      } else {
        val = newVal
      }
      childOb = !shallow && observe(newVal)
      dep.notify()
    }
  })
}

这个函数主要的职责是建立起某个对象属性的get 和 set 钩子,并且通过 observe 函数来获取该对象的 Observer 对象,新建一个数据依赖 Dep。 在 get 钩子函数中则去处理数据依赖和 Watcher 的关联,在 set 中调用依赖的 notify 函数通知关联的 Watcher 去运行回调函数。

总结

到现在为止,已经差不多理清了 Vue 数据绑定的大体逻辑,但是仍然还有很多遗留问题,比如:Dep 和 Watcher 是怎么建立联系的,不同的 Watcher 都是在何时建立的,Watcher 的 getter 函数具体都有哪些,这些问题会在以后的文章中详细说明。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,569评论 4 363
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,499评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,271评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,087评论 0 209
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,474评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,670评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,911评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,636评论 0 202
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,397评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,607评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,093评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,418评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,074评论 3 237
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,092评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,865评论 0 196
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,726评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,627评论 2 270

推荐阅读更多精彩内容