vue生命周期源码分析

1,040 阅读3分钟

Vue.js另一个核心思想是组件化。组件化就是把页面拆分成多个组件(component),每个组件依赖的css,js,模板,图片等都放在一起去开发和维护,而且组件资源独立,组件在系统内部可复用,组件与组件之间可以嵌套。

每个Vue实例在被创建之前都要经过一系列的初始化过程,同时在这个过程中也会运行一些生命周期钩子函数。在vue官网有一张生命周期的图,

我们现在通过源码的分析来看看这些个生命周期执行的时机是怎么样的。

源码中最终执行生命周期的函数都是调用callHook方法,在src/core/instance/lifecycle.js中

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函数的功能就是调用某个生命周期钩子注册的所有回调函数。

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钩子函数。

下面我们来看下挂载时候的生命周期函数

beforeMount和mounted

beforeMount钩子函数发生在mounted之前,也就是DOM挂载之前,它的调用是在mountComponent函数中,

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中,

  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中:

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