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钩子函数中能够作一些销毁工做。更好得利用合适的生命周期去作合适的事。

相关文章
相关标签/搜索