天天看點

vue: created,watch,computed執行順序

作者:易創空間棧

舉個‬例子:

// main.js
import Vue from "vue";

new Vue({
  el: "#app",
  template: `<div>
    <div>{{computedCount}}</div>
  </div>`,
  data() {
    return {
      count: 1,
    }
  },
  watch: {
    count: {
      handler() {
        console.log('watch');
      },
      immediate: true,
    }
  },
  computed: {
    computedCount() {
      console.log('computed');
      return this.count + 1;
    }
  },
  created() {
    console.log('created');
  },
});           

目前例子的執行順序為:watch --> created --> computed。

在new Vue的執行個體化過程中,會執行初始化方法this._init,其中有代碼:

Vue.prototype._init = function (options) {
    // ...
    initState(vm);
    // ...
    callHook(vm, 'created');
    // ...
    if (vm.$options.el) {
      vm.$mount(vm.$options.el);
    }
}

function initState (vm) {
  vm._watchers = [];
  var opts = vm.$options;
  if (opts.props) { initProps(vm, opts.props); }
  if (opts.methods) { initMethods(vm, opts.methods); }
  if (opts.data) {
    initData(vm);
  } else {
    observe(vm._data = {}, true /* asRootData */);
  }
  if (opts.computed) { initComputed(vm, opts.computed); }
  if (opts.watch && opts.watch !== nativeWatch) {
    initWatch(vm, opts.watch);
  }
}
           

猛一看代碼,是不是發現先執行的initComputed(vm, opts.computed),然後執行initWatch(vm, opts.watch),再執行callHook(vm, 'created'),那為啥不是computed --> watch --> created呢?

1、關于initComputed

const computedWatcherOptions = { lazy: true }
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 (!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') {
        // ...
    }
  }
}
           

在通過initComputed初始化計算屬性的時候,通過周遊的方式去處理目前元件中的computed。首先,在進行計算屬性執行個體化的時候,将{ lazy: true }作為參數傳入,并且執行個體化的Watcher中的getter就是目前例子中的computedCount函數;其次,通過defineComputed(vm, key, userDef)的方式在目前元件執行個體vm上為key進行userDef的處理。具體為:

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
  }
  // ...
  Object.defineProperty(target, key, sharedPropertyDefinition)
}

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

從以上可以看出,這裡通過Object.defineProperty(target,key,sharedPropertyDefinition)的方式,将函數computedGetter作為get函數,隻有當對key進行通路的時候,才會觸發其内部的邏輯。内部邏輯watcher.evaluate()為:

evaluate () {
    this.value = this.get()
    this.dirty = false
}
           

get中有主要邏輯:

value = this.getter.call(vm, vm)
           

這裡的this.getter就是目前例子中的:

computedCount() {
  console.log('computed');
  return this.count + 1;
}
           

也就是說,隻有當擷取computedCount的時候才會觸發computed的計算,也就是在進行vm.$mount(vm.$options.el)階段才會執行到console.log('computed')。

2、關于initWatch

function initWatch (vm: Component, watch: Object) {
  for (const key in watch) {
    const handler = watch[key]
    if (Array.isArray(handler)) {
      for (let i = 0; i < handler.length; i++) {
        createWatcher(vm, key, handler[i])
      }
    } else {
      createWatcher(vm, key, handler)
    }
  }
}
function createWatcher (
  vm: Component,
  expOrFn: string | Function,
  handler: any,
  options?: Object
) {
  if (isPlainObject(handler)) {
    options = handler
    handler = handler.handler
  }
  if (typeof handler === 'string') {
    handler = vm[handler]
  }
  return vm.$watch(expOrFn, handler, options)
}
           

在通過initWatch初始化偵聽器的時候,如果watch為數組,則周遊執行createWatcher,否則直接執行createWatcher。如果handler是對象或者字元串時,将其進行處理,最終作為參數傳入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
    const watcher = new Watcher(vm, expOrFn, cb, options)
    if (options.immediate) {
      try {
        cb.call(vm, watcher.value)
      } catch (error) {
        handleError(error, vm, `callback for immediate watcher "${watcher.expression}"`)
      }
    }
    return function unwatchFn () {
      watcher.teardown()
    }
  }
           

這裡擷取到的options中會有immediate: true的鍵值,同時通過options.user = true設定user為true,再将其作為參數傳入去進行Watcher的執行個體化。

目前例子中options.immediate為true,是以會執行cb.call(vm, watcher.value),也就是以vm為主體,立刻執行cb。目前例子中cb就是handler:

handler() {
    console.log('watch');
},
           

這裡就解釋了目前例子中console.log('watch')是最先執行的。

然後,執行完initComputed和initWatch以後,就會通過callHook(vm, 'created')執行到生命周期中的console.log('created')了。

最後通過vm.$mount(vm.$options.el)進行頁面渲染的時候,會先去建立vNode,這時就需要擷取到computedCount的值,進而觸發其get函數的後續邏輯,最終執行到console.log('computed')。

總結

關于vue中created和watch的執行順序相對比較簡單,而其中computed是通過Object.defineProperty為目前vm進行定義,再到後續建立vNode階段才去觸發執行其get函數,最終執行到計算屬性computed對應的邏輯。

繼續閱讀