vue生命週期源碼分析

Vue.js另外一個核心思想是組件化。組件化就是把頁面拆分紅多個組件(component),每一個組件依賴的css,js,模板,圖片等都放在一塊兒去開發和維護,並且組件資源獨立,組件在系統內部可複用,組件與組件之間能夠嵌套。css

每一個Vue實例在被建立以前都要通過一系列的初始化過程,同時在這個過程當中也會運行一些生命週期鉤子函數。在vue官網有一張生命週期的圖,vue

咱們如今經過源碼的分析來看看這些個生命週期執行的時機是怎麼樣的。

源碼中最終執行生命週期的函數都是調用callHook方法,在src/core/instance/lifecycle.js中node

export function callHook (vm: Component, hook: string) {
  // #7573 disable dep collection when invoking lifecycle hooks
  pushTarget()
  const handlers = vm.$options[hook]
  if (handlers) {
    for (let i = 0, j = handlers.length; i < j; i++) {
      try {
        handlers[i].call(vm)
      } catch (e) {
        handleError(e, vm, `${hook} hook`)
      }
    }
  }
  if (vm._hasHookEvent) {
    vm.$emit('hook:' + hook)
  }
  popTarget()
}
複製代碼

傳入兩個參數值,一個是組件式的實例,一個是字符串hook,handlers是一個數組,數組每個元素是一個生命週期函數,若是handlers有值則進行遍歷,而後就會去執行每個生命週期的鉤子函數,同時把咱們當前的vm實例做爲當前的上下文傳入,這樣在咱們編寫生命週期函數裏面的this就指向了vue實例。 因此說callhook函數的功能就是調用某個生命週期鉤子註冊的全部回調函數。vue-router

beforeCreate&created

beforeCreate和created函數都是在實例化VUE的階段,在_init方法中執行的,它的定義在src/core/instance/init.js中,後端

Vue.prototype._init = function (options?: Object) {
    ...
      initLifecycle(vm)
    initEvents(vm)
    initRender(vm)
    callHook(vm, 'beforeCreate')
    initInjections(vm) // resolve injections before data/props
    initState(vm)
    initProvide(vm) // resolve provide after data/props
    callHook(vm, 'created')
    ...
}
複製代碼

咱們能夠看到在初始化的時候執行了beforeCreate和created兩個鉤子函數,它們兩個都是在initState的先後調用的,initState的做用是初始化props、data、methods、watch、computed等,因此在beforeCreate的鉤子中就不能獲取到props、data中定義的值,也不能調用methods中定義的函數。這兩個鉤子函數執行的時候呢,並無渲染DOM,因此咱們也不能訪問DOM,通常來講,若是組件在加載的時候須要和後端有交互,放在這兩個鉤子函數執行均可以,若是須要訪問props,data等數據的話,就須要使用created鉤子函數。數組

下面咱們來看下掛載時候的生命週期函數bash

beforeMount和mounted

beforeMount鉤子函數發生在mounted以前,也就是DOM掛載以前,它的調用是在mountComponent函數中,markdown

export function mountComponent (
  vm: Component,
  el: ?Element,
  hydrating?: boolean
): Component {
  vm.$el = el
  if (!vm.$options.render) {
    vm.$options.render = createEmptyVNode
    if (process.env.NODE_ENV !== 'production') {
      /* istanbul ignore if */
      if ((vm.$options.template && vm.$options.template.charAt(0) !== '#') ||
        vm.$options.el || el) {
        warn(
          'You are using the runtime-only build of Vue where the template ' +
          'compiler is not available. Either pre-compile the templates into ' +
          'render functions, or use the compiler-included build.',
          vm
        )
      } else {
        warn(
          'Failed to mount component: template or render function not defined.',
          vm
        )
      }
    }
  }
  callHook(vm, 'beforeMount')

  let updateComponent
  /* istanbul ignore if */
  if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
    updateComponent = () => {
      const name = vm._name
      const id = vm._uid
      const startTag = `vue-perf-start:${id}`
      const endTag = `vue-perf-end:${id}`

      mark(startTag)
      const vnode = vm._render()
      mark(endTag)
      measure(`vue ${name} render`, startTag, endTag)

      mark(startTag)
      vm._update(vnode, hydrating)
      mark(endTag)
      measure(`vue ${name} patch`, startTag, endTag)
    }
  } else {
    updateComponent = () => {
      vm._update(vm._render(), hydrating)
    }
  }

  // we set this to vm._watcher inside the watcher's constructor // since the watcher's initial patch may call $forceUpdate (e.g. inside child
  // component's mounted hook), which relies on vm._watcher being already defined new Watcher(vm, updateComponent, noop, { before () { if (vm._isMounted) { callHook(vm, 'beforeUpdate') } } }, true /* isRenderWatcher */) hydrating = false // manually mounted instance, call mounted on self // mounted is called for render-created child components in its inserted hook if (vm.$vnode == null) { vm._isMounted = true callHook(vm, 'mounted') } return vm } 複製代碼

在執行vm._render()函數渲染VNode以前,執行了beforeMount鉤子函數,在執行完vm._update()把VNode patch到真實DOM後,執行mounted鉤子。這裏判斷了若是vm.$vnode爲null,則代表這不是一次組件的初始化過程,而是經過外部new Vue初始化過程。那麼對於組件,它的mounted時機在哪呢?咱們看到組件的VNode patch到DOM 後,會執行invokeInsertHook函數,把invokeInsertHook裏保存的鉤子函數依次執行一遍,它在src/core/vdom/patch.js中,dom

function invokeInsertHook (vnode, queue, initial) {
    // delay insert hooks for component root nodes, invoke them after the
    // element is really inserted
    if (isTrue(initial) && isDef(vnode.parent)) {
      vnode.parent.data.pendingInsert = queue
    } else {
      for (let i = 0; i < queue.length; ++i) {
        queue[i].data.hook.insert(queue[i])
      }
    }
  }
複製代碼

該函數會執行insert這個鉤子函數,對於組件而言,insert鉤子函數的定義在src/core/vdom/create-component.js中componentVNodeHooks中:ide

insert (vnode: MountedComponentVNode) {
    const { context, componentInstance } = vnode
    if (!componentInstance._isMounted) {
      componentInstance._isMounted = true
      callHook(componentInstance, 'mounted')
    }
    if (vnode.data.keepAlive) {
      if (context._isMounted) {
        // vue-router#1212
        // During updates, a kept-alive component's child components may // change, so directly walking the tree here may call activated hooks // on incorrect children. Instead we push them into a queue which will // be processed after the whole patch process ended. queueActivatedComponent(componentInstance) } else { activateChildComponent(componentInstance, true /* direct */) } } }, 複製代碼

每一個子組件都是在這個鉤子函數中執行mounted鉤子函數,而且insertedVnodeQueue的添加順序是先子後父,因此對於同步渲染的子組件而言,mounted鉤子函數的執行順序也是先子後父。beforeMount呢而是先父後子,由於調用mountComponent是優先執行父組件,而後再執行子組件的patch,再去執行子組件的beforeMount。

beforeUpdate & updated

beforeUpdate和updated的鉤子函數執行時機都應該是在數據更新的時候,

export function mountComponent (
    ...
     // we set this to vm._watcher inside the watcher's constructor // since the watcher's initial patch may call $forceUpdate (e.g. inside child
      // component's mounted hook), which relies on vm._watcher being already defined new Watcher(vm, updateComponent, noop, { before () { if (vm._isMounted) { callHook(vm, 'beforeUpdate') } } }, true /* isRenderWatcher */) ... ) 複製代碼

beforeUpdate的執行時機是在渲染Watcher的before函數中,這裏有個判斷,也就是在組件已經mounted以後,纔會去調用這個鉤子函數。update的執行時機是在flushSchedulerQueue函數調用的時候,它的定義在src/core/observe/scheduler.js中,

function flushSchedulerQueue () {
    ...
    // 獲取到 updatedQueue
    callUpdatedHooks(updatedQueue)
    function callUpdatedHooks (queue) {
      let i = queue.length
      while (i--) {
        const watcher = queue[i]
        const vm = watcher.vm
        if (vm._watcher === watcher && vm._isMounted) {
          callHook(vm, 'updated')
        }
      }
    }
}
複製代碼

updateQueue是更新了watcher數組,那麼在callUpdatedHooks函數中,它對這些數組作遍歷,只有知足當前watcher爲vm._watcher以及組件已經mounted這兩個條件,纔會執行updated鉤子函數。 在組件mount的過程當中,會實例化一個渲染的watcher去監聽vm上的數據變化從新渲染,這段邏輯發生在mountComponent函數執行的時候,

export function mountComponent (
  vm: Component,
  el: ?Element,
    hydrating?: boolean
): Component {
  // ...
  let updateComponent = () => {
      vm._update(vm._render(), hydrating)
  }
  new Watcher(vm, updateComponent, noop, {
    before () {
      if (vm._isMounted) {
        callHook(vm, 'beforeUpdate')
      }
    }
  }, true /* isRenderWatcher */)
  // ...
}
複製代碼

那麼在實例化watcher的過程當中,在它的構造函數裏會判斷isRenderWatcher,接着把當前watcher的實例賦值給vm._watcher,在src/core/observer/wathcer.js中

export default class Watcher {
    ...
    constructor (
        vm: Component,
        expOrFn: string | Function,
        cb: Function,
        options?: ?Object,
        isRenderWatcher?: boolean
      ) {
        this.vm = vm
        if (isRenderWatcher) {
          vm._watcher = this
        }
        vm._watchers.push(this)
    }
    ...
    
}
複製代碼

把當前watcher實例push到vm._watchers中,vm._watcher是專門用來監聽vm上數據變化而後從新渲染的,因此它是一個渲染相關的watcher,所以在callUpdatedHooks函數中,只有vm._watcher的回調執行完畢後,纔會執行updated鉤子函數。

beforeDestroy & destroyed

beforeDestroy和destroyed鉤子函數的執行時機在組件銷燬的階段,在src/core/instance/lifecycle.js中,

Vue.prototype.$destroy = function () {
    const vm: Component = this
    if (vm._isBeingDestroyed) {
      return
    }
    callHook(vm, 'beforeDestroy')
    vm._isBeingDestroyed = true
    // remove self from parent
    const parent = vm.$parent
    if (parent && !parent._isBeingDestroyed && !vm.$options.abstract) {
      remove(parent.$children, vm)
    }
    // teardown watchers
    if (vm._watcher) {
      vm._watcher.teardown()
    }
    let i = vm._watchers.length
    while (i--) {
      vm._watchers[i].teardown()
    }
    // remove reference from data ob
    // frozen object may not have observer.
    if (vm._data.__ob__) {
      vm._data.__ob__.vmCount--
    }
    // call the last hook...
    vm._isDestroyed = true
    // invoke destroy hooks on current rendered tree
    vm.__patch__(vm._vnode, null)
    // fire destroyed hook
    callHook(vm, 'destroyed')
    // turn off all instance listeners.
    vm.$off()
    // remove __vue__ reference
    if (vm.$el) {
      vm.$el.__vue__ = null
    }
    // release circular reference (#6759)
    if (vm.$vnode) {
      vm.$vnode.parent = null
    }
  }
複製代碼

beforeDestroy鉤子函數的執行時機是在destroy函數執行最開始的地方,接着執行了一系列的銷燬動做,包括從parent的children中刪掉自身,刪掉watcher,當前渲染的VNode執行銷燬鉤子函數等,執行完畢後再調用destroy鉤子函數。在$destroy的執行過程當中,它又會執行vm.patch(vm.vnode,null)觸發它子組件的銷燬鉤子函數,這樣一層層的遞歸調用,因此destroy鉤子函數執行順序是先子後父,和mounted過程同樣。

以上呢介紹了Vue生命週期中各個鉤子函數的執行時機以及順序,經過分析,咱們知道了如在created鉤子函數中能夠訪問數據,在mounted鉤子函數中能夠訪問DOM,在destroy鉤子函數中能夠作一些銷燬工做。更好得利用合適的生命週期去作合適的事。

相關文章
相關標籤/搜索