Vue源碼簡析之Watcher(下)

本文聊聊另外一種watcher:computedWatcher的實現。express

使用方式

<template>
  <div class="container">
    <div>{{fullname}}</div>
  </div>
</template>

<script>
import child from './components/child'
export default {
  name: 'App',
  data(vm) {
    return {
      firstname: 'klay',
      lastname: 'thompson'
    }
  },
  computed: {
    fullname() {
      return this.firstname + this.lastname
    }
  },
 }
複製代碼

這裏定義一個fullname的計算屬性,根據firstnamelastname的值計算值,當這兩個值發生變化時fullname會從新計算bash

initState

// core/instance/state.js
export function initState (vm: Component) {
  vm._watchers = []
  const opts = vm.$options
  ...
  if (opts.computed) initComputed(vm, opts.computed)
  ...
}
複製代碼

initComputed

// core/instance/state.js
function initComputed (vm: Component, computed: Object) {
  // $flow-disable-line
  const watchers = vm._computedWatchers = Object.create(null)
  // computed properties are just getters during SSR
  const isSSR = isServerRendering()

  for (const key in computed) {
    const userDef = computed[key]
    const getter = typeof userDef === 'function' ? userDef : userDef.get
    if (process.env.NODE_ENV !== 'production' && getter == null) {
      warn(
        `Getter is missing for computed property "${key}".`,
        vm
      )
    }

    if (!isSSR) {
      // create internal watcher for the computed property.
      watchers[key] = new Watcher(
        vm,
        getter || noop,
        noop,
        computedWatcherOptions
      )
    }

    // component-defined computed properties are already defined on the
    // component prototype. We only need to define computed properties defined
    // at instantiation here.
    if (!(key in vm)) {
      defineComputed(vm, key, userDef)
    } else if (process.env.NODE_ENV !== 'production') {
      if (key in vm.$data) {
        warn(`The computed property "${key}" is already defined in data.`, vm)
      } else if (vm.$options.props && key in vm.$options.props) {
        warn(`The computed property "${key}" is already defined as a prop.`, vm)
      }
    }
  }
}
複製代碼
  • 遍歷computed對象,根據key生成對應的watcher對象並保存在vm._computedWatchers,這裏的computedWatcherOptions = { lazy: true }
  • 調用defineComputed方法,給vm對象添加key

defineComputed

// core/instance/state.js
export function defineComputed ( target: any, key: string, userDef: Object | Function ) {
  const shouldCache = !isServerRendering()
  if (typeof userDef === 'function') {
    sharedPropertyDefinition.get = shouldCache
      ? createComputedGetter(key)
      : createGetterInvoker(userDef)
    sharedPropertyDefinition.set = noop
  } else {
    sharedPropertyDefinition.get = userDef.get
      ? shouldCache && userDef.cache !== false
        ? createComputedGetter(key)
        : createGetterInvoker(userDef.get)
      : noop
    sharedPropertyDefinition.set = userDef.set || noop
  }
  ...
  Object.defineProperty(target, key, sharedPropertyDefinition)
}
複製代碼

這裏typeof userDef === 'function'且不是服務端渲染,因此會走sharedPropertyDefinition.get = createComputedGetter(key),sharedPropertyDefinition就是一個公用的propertyDescriptor函數

const sharedPropertyDefinition = {
  enumerable: true,
  configurable: true,
  get: noop,
  set: noop
}
複製代碼

createComputedGetter

function createComputedGetter (key) {
  return function computedGetter () {
    const watcher = this._computedWatchers && this._computedWatchers[key]
    if (watcher) {
      if (watcher.dirty) {
        watcher.evaluate()
      }
      if (Dep.target) {
        watcher.depend()
      }
      return watcher.value
    }
  }
}
複製代碼

當getter觸發時,根據key拿到對應的watcher,判斷watcher依賴的值是否有更新,有則計算值,最後返回watcher的value。oop

evaluate

// core/observer/watcher.js
/** * Evaluate the value of the watcher. * This only gets called for lazy watchers. */
evaluate () {
    this.value = this.get()
    this.dirty = false
}
複製代碼

evaluate方法專門爲computedWatcher服務的ui

// // core/observer/watcher.js
get () {
    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()
    }
    return value
  }
複製代碼

這裏的this.getter就是前面的userDef,進行求值時會觸發依賴項的依賴收集,之前面的例子來看,firstnamelastname會將fullname對應的watcher收集。當這兩個值中任意一個發生變化時就會觸發watcher的從新計算。this

幾個注意的點

getter何時觸發的

Vue經過在Vm實例上定義getter,在getter裏面計算watcher的值,那麼確定有Vm.fullname這樣的取值語句觸發getter,這是在哪一個地方觸發的呢?lua

  1. render函數,在mount過程當中會執行render函數,裏面有vm.fullname的求值。
  2. 若是沒有在頁面中使用計算屬性,在method中有this.fullname也是同樣。

computedWatcher的update
// core/observer/watcher.js
  update () {
    /* istanbul ignore else */
    if (this.lazy) {
      this.dirty = true
    } else if (this.sync) {
      this.run()
    } else {
      queueWatcher(this)
    }
  }
複製代碼

computedWatcher的update方法並不會將當前watcher添加進queue,只是將watcher的dirty標記爲true,在nextTick時render函數再次執行,再看一遍前面的getter取值spa

//core/instance/state.js
function createComputedGetter (key) {
  return function computedGetter () {
    const watcher = this._computedWatchers && this._computedWatchers[key]
    if (watcher) {
      if (watcher.dirty) {
        watcher.evaluate()
      }
      if (Dep.target) {
        watcher.depend()
      }
      return watcher.value
    }
  }
}
複製代碼
method vs computed

官網中也有描述,computed的功能用method也能夠實現,好比咱們改寫前面的例子prototype

<template>
  <div class="container">
    <div>{{fullname()}}</div>
  </div>
</template>

<script>
import child from './components/child'
export default {
  name: 'App',
  data(vm) {
    return {
      firstname: 'klay',
      lastname: 'thompson'
    }
  },
  methods: {
    fullname() {
      return this.firstname + this.lastname
    }
  },
 }
複製代碼

method雖然實現了功能,可是這裏有個問題,不管fristnamelastname是否變化,求值函數都會執行一遍,假設這個取值過程十分複雜,在依賴的值沒有變化時從新計算是沒有必要的,這種狀況下采用computed更合理,watcher.dirty === false,不會從新計算3d

總結

相關文章
相關標籤/搜索