生命周期

    源码中最终执行生命周期的函数都是调用 方法,它的定义在 src/core/instance/lifecycle 中:

    callHook 函数的逻辑很简单,根据传入的字符串 hook,去拿到 vm.$options[hook] 对应的回调函数数组,然后遍历执行,执行的时候把 vm 作为函数执行的上下文。

    在上一节中,我们详细地介绍了 Vue.js 合并 options 的过程,各个阶段的生命周期的函数也被合并到 vm.$options 里,并且是一个数组。因此 callhook 函数的功能就是调用某个生命周期钩子注册的所有回调函数。

    了解了生命周期的执行方式后,接下来我们会具体介绍每一个生命周期函数它的调用时机。

    beforeCreatecreated 函数都是在实例化 Vue 的阶段,在 _init 方法中执行的,它的定义在 src/core/instance/init.js 中:

    1. Vue.prototype._init = function (options?: Object) {
    2. // ...
    3. initLifecycle(vm)
    4. initEvents(vm)
    5. initRender(vm)
    6. callHook(vm, 'beforeCreate')
    7. initInjections(vm) // resolve injections before data/props
    8. initState(vm)
    9. initProvide(vm) // resolve provide after data/props
    10. callHook(vm, 'created')
    11. // ...
    12. }

    可以看到 beforeCreatecreated 的钩子调用是在 initState 的前后,initState 的作用是初始化 propsdatamethodswatchcomputed 等属性,之后我们会详细分析。那么显然 beforeCreate 的钩子函数中就不能获取到 propsdata 中定义的值,也不能调用 methods 中定义的函数。

    在这俩个钩子函数执行的时候,并没有渲染 DOM,所以我们也不能够访问 DOM,一般来说,如果组件在加载的时候需要和后端有交互,放在这俩个钩子函数执行都可以,如果是需要访问 propsdata 等数据的话,就需要使用 created 钩子函数。之后我们会介绍 vue-router 和 vuex 的时候会发现它们都混合了 beforeCreatd 钩子函数。

    beforeMount & mounted

    顾名思义,beforeMount 钩子函数发生在 mount,也就是 DOM 挂载之前,它的调用时机是在 mountComponent 函数中,定义在 src/core/instance/lifecycle.js 中:

    1. export function mountComponent (
    2. vm: Component,
    3. el: ?Element,
    4. hydrating?: boolean
    5. ): Component {
    6. vm.$el = el
    7. // ...
    8. callHook(vm, 'beforeMount')
    9. let updateComponent
    10. /* istanbul ignore if */
    11. if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
    12. updateComponent = () => {
    13. const name = vm._name
    14. const id = vm._uid
    15. const startTag = `vue-perf-start:${id}`
    16. const endTag = `vue-perf-end:${id}`
    17. mark(startTag)
    18. const vnode = vm._render()
    19. mark(endTag)
    20. measure(`vue ${name} render`, startTag, endTag)
    21. mark(startTag)
    22. vm._update(vnode, hydrating)
    23. mark(endTag)
    24. measure(`vue ${name} patch`, startTag, endTag)
    25. } else {
    26. updateComponent = () => {
    27. vm._update(vm._render(), hydrating)
    28. }
    29. // we set this to vm._watcher inside the watcher's constructor
    30. // since the watcher's initial patch may call $forceUpdate (e.g. inside child
    31. // component's mounted hook), which relies on vm._watcher being already defined
    32. new Watcher(vm, updateComponent, noop, {
    33. before () {
    34. if (vm._isMounted) {
    35. callHook(vm, 'beforeUpdate')
    36. }
    37. }
    38. }, true /* isRenderWatcher */)
    39. hydrating = false
    40. // manually mounted instance, call mounted on self
    41. // mounted is called for render-created child components in its inserted hook
    42. if (vm.$vnode == null) {
    43. vm._isMounted = true
    44. callHook(vm, 'mounted')
    45. }
    46. return vm
    47. }

    之前我们提到过,组件的 VNode patch 到 DOM 后,会执行 invokeInsertHook 函数,把 insertedVnodeQueue 里保存的钩子函数依次执行一遍,它的定义在 src/core/vdom/patch.js 中:

    该函数会执行 insert 这个钩子函数,对于组件而言,insert 钩子函数的定义在 src/core/vdom/create-component.js 中的 componentVNodeHooks 中:

    1. const componentVNodeHooks = {
    2. // ...
    3. insert (vnode: MountedComponentVNode) {
    4. const { context, componentInstance } = vnode
    5. if (!componentInstance._isMounted) {
    6. componentInstance._isMounted = true
    7. callHook(componentInstance, 'mounted')
    8. }
    9. // ...
    10. },
    11. }

    我们可以看到,每个子组件都是在这个钩子函数中执行 mouted 钩子函数,并且我们之前分析过,insertedVnodeQueue 的添加顺序是先子后父,所以对于同步渲染的子组件而言,mounted 钩子函数的执行顺序也是先子后父。

    顾名思义,beforeUpdateupdated 的钩子函数执行时机都应该是在数据更新的时候,到目前为止,我们还没有分析 Vue 的数据双向绑定、更新相关,下一章我会详细介绍这个过程。

    beforeUpdate 的执行时机是在渲染 Watcher 的 before 函数中,我们刚才提到过:

    1. export function mountComponent (
    2. vm: Component,
    3. el: ?Element,
    4. hydrating?: boolean
    5. ): Component {
    6. // ...
    7. // we set this to vm._watcher inside the watcher's constructor
    8. // component's mounted hook), which relies on vm._watcher being already defined
    9. new Watcher(vm, updateComponent, noop, {
    10. before () {
    11. if (vm._isMounted) {
    12. callHook(vm, 'beforeUpdate')
    13. }
    14. }
    15. }, true /* isRenderWatcher */)
    16. // ...
    17. }

    注意这里有个判断,也就是在组件已经 mounted 之后,才会去调用这个钩子函数。

    update 的执行时机是在flushSchedulerQueue 函数调用的时候, 它的定义在 src/core/observer/scheduler.js 中:

    函数我们之后会详细介绍,可以先大概了解一下,updatedQueue 是 更新了的 wathcer 数组,那么在 callUpdatedHooks 函数中,它对这些数组做遍历,只有满足当前 watchervm._watcher 以及组件已经 mounted 这两个条件,才会执行 updated 钩子函数。

    1. export function mountComponent (
    2. vm: Component,
    3. el: ?Element,
    4. hydrating?: boolean
    5. ): Component {
    6. // ...
    7. // 这里是简写
    8. let updateComponent = () => {
    9. vm._update(vm._render(), hydrating)
    10. }
    11. new Watcher(vm, updateComponent, noop, {
    12. before () {
    13. if (vm._isMounted) {
    14. callHook(vm, 'beforeUpdate')
    15. }
    16. }
    17. }, true /* isRenderWatcher */)
    18. // ...
    19. }

    那么在实例化 Watcher 的过程中,在它的构造函数里会判断 isRenderWatcher,接着把当前 watcher 的实例赋值给 vm._watcher,定义在 src/core/observer/watcher.js 中:

    1. export default class Watcher {
    2. // ...
    3. constructor (
    4. vm: Component,
    5. expOrFn: string | Function,
    6. cb: Function,
    7. options?: ?Object,
    8. isRenderWatcher?: boolean
    9. ) {
    10. this.vm = vm
    11. if (isRenderWatcher) {
    12. vm._watcher = this
    13. }
    14. vm._watchers.push(this)
    15. // ...
    16. }

    同时,还把当前 wathcer 实例 push 到 vm._watchers 中,vm._watcher 是专门用来监听 vm 上数据变化然后重新渲染的,所以它是一个渲染相关的 watcher,因此在 callUpdatedHooks 函数中,只有 vm._watcher 的回调执行完毕后,才会执行 updated 钩子函数。

    beforeDestroy & destroyed

    顾名思义,beforeDestroydestroyed 钩子函数的执行时机在组件销毁的阶段,组件的销毁过程之后会详细介绍,最终会调用 $destroy 方法,它的定义在 src/core/instance/lifecycle.js 中:

    beforeDestroy 钩子函数的执行时机是在 $destroy 函数执行最开始的地方,接着执行了一系列的销毁动作,包括从 parent$children 中删掉自身,删除 watcher,当前渲染的 VNode 执行销毁钩子函数等,执行完毕后再调用 destroy 钩子函数。

    $destroy 的执行过程中,它又会执行 vm.patch(vm._vnode, null) 触发它子组件的销毁钩子函数,这样一层层的递归调用,所以 destroy 钩子函数执行顺序是先子后父,和 mounted 过程一样。

    activateddeactivated 钩子函数是专门为 keep-alive 组件定制的钩子,我们会在介绍 keep-alive 组件的时候详细介绍,这里先留个悬念。

    总结

    这一节主要介绍了 Vue 生命周期中各个钩子函数的执行时机以及顺序,通过分析,我们知道了如在 created 钩子函数中可以访问到数据,在 钩子函数中可以访问到 DOM,在 destroy 钩子函数中可以做一些定时器销毁工作,了解它们有利于我们在合适的生命周期去做不同的事情。