vue源碼分析系列之響應式數據(四)

前言

上一節着重講述了initComputed中的代碼,以及數據是如何從computed中到視圖層的,以及data修改後如何作用於computed。這一節主要記錄initWatcher中的內容。

正文

demo修改

之前的new Vue(options)的options中,我們可以觀察到computed,data,但是對於watch是沒法演示的,所以我們在代碼中加入一段可以觀察到watch初始化以及效果的代碼。

{
  watch: {
    a(newV,oldV) {
      console.log(`${oldV} -> ${newV}`);
    }
  }
}

依舊是觀察a這個變量,當點擊+1按鈕時候,即可讓a變化。

入口

if (opts.watch && opts.watch !== nativeWatch) {
  initWatch(vm, opts.watch);
}

initWatch

function initWatch (vm: Component, watch: Object) {
  for (const key in watch) {
    // 拿到watch中相關的處理邏輯
    const handler = watch[key]
    // 如果是個數組,就挨個創建watcher
    if (Array.isArray(handler)) {
      for (let i = 0; i < handler.length; i++) {
        createWatcher(vm, key, handler[i])
      }
    } else {
      // 否則直接初始化,我們此次例子中會直接走這裏
      // createWatcher(vm, a, fn)
      createWatcher(vm, key, handler)
    }
  }
}

createWatcher

function createWatcher (
  vm: Component,
  keyOrFn: string | Function,
  handler: any,
  options?: Object
) {
  // 這裏只是對不同創建形式的標準化。
  if (isPlainObject(handler)) {
    options = handler
    handler = handler.handler
  }
  if (typeof handler === 'string') {
    handler = vm[handler]
  }
  // 最終這裏是真正監聽值變化的地方。
  // $watch(a, handle, undefined);
  return vm.$watch(keyOrFn, handler, options)
}

vm.$watch

Vue.prototype.$watch = function (
    expOrFn: string | Function,
    cb: any,
    options?: Object
  ): Function {
    const vm: Component = this
    if (isPlainObject(cb)) {
      return createWatcher(vm, expOrFn, cb, options)
    }
    options = options || {}
    options.user = true
    // 主要是這裏創建一個觀察者
    // new Watcher(vm, 'a', handle, {user: true})
    const watcher = new Watcher(vm, expOrFn, cb, options)
    if (options.immediate) {
      cb.call(vm, watcher.value)
    }
    return function unwatchFn () {
      watcher.teardown()
    }
  }

new Watcher

watcher,即觀察者,是我們多次提到的一個東西。這裏主要強調的是watcher.get()中的內容。

class Watcher {
  constructor (
    vm: Component,
    expOrFn: string | Function,
    cb: Function,
    options?: Object
  ) {
    // 一堆初始化信息
    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.value = this.lazy
      ? undefined
      : this.get()
  }

  get () {
    // 將當前watcher設爲Dep.target方便後面訪問a的getter時候,
    // 設定爲a的依賴
    pushTarget(this)
    let value
    const vm = this.vm
    try {
      // 求a的值。並把當前watcher加入a的依賴中。
      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()
    }
    return value
  }
}

run watcher

到上一步,監聽a的watcher已經初始化完畢了,當a因爲點擊鼠標變化時候,會觸發這個watcher的變化。執行watcher的run方法,我們繼續來看下run方法裏的內容。

class Watcher {
  run () {
    if (this.active) {
      // 求a的最新值。
      const value = this.get()
      if (
        value !== this.value ||
        // Deep watchers and watchers on Object/Arrays should fire even
        // when the value is the same, because the value may
        // have mutated.
        isObject(value) ||
        this.deep
      ) {
        // 當a變的時候,將舊值賦給oldValue。
        const oldValue = this.value
        // this.value賦予最新的值。
        this.value = value
        // 用戶定義的watch調用時加入try,catch。
        if (this.user) {
          try {
            // 執行當時傳入的回調,並將新值與舊值一併傳入。
            this.cb.call(this.vm, value, oldValue)
          } catch (e) {
            handleError(e, this.vm, `callback for watcher "${this.expression}"`)
          }
        } else {
          this.cb.call(this.vm, value, oldValue)
        }
      }
    }
  }
}

總結

至此,watch,監聽屬性的這一部分已經完結,本質上就是對於每個監聽的屬性,創建一個watcher。當watcher改變時候,會觸發開發者定義的回調。通過前兩篇文章的學習,這篇應該算是很理解的內容。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章