vue源码解读--生命周期
首先,改动我们的示例代码为

我们之前分析的时候不乏看到过这些代码

因此callHook就是调用生命周期钩子的代码

接收参数为
('组件实例',生命周期钩子函数名称)
a-首先调用pushTarget

b-经过查找发现,只有在watcher中调用get方法时target才有值,而get的调用是在update中,也就是说,在init-mount-render过程中凡是调用该函数的地方,统一为undefined,同时,当执行子组件init时已经在父组件中执行update,故子组件的target是有值的
c-handlers;取自vm.$options[hook],我们知道在init过程中会执行mergeOption,当存在生命周期钩子时会进行挂载,则这里相当于获取到vm.$option.beforeCreate等
d-info=beforeCreatehook、createdhook等,作为new vue的init,为beforeCreatehook
e-遍历钩子函数;由于在合并代码的时候当parent和child都存在同名钩子时执行的是concat,因此这里可能不止一个
调用invokeWithErrorHandling,传参为(beforeCreate函数、vue、null、vue、beforeCreateHook)

调用beforeCreate函数,此时控制台将打印输出

f-vm._hasHookEvent;经过查找分析我们知道,在执行new vue的init过程中调用initEvents置为false

而置为true的条件是

因此,为true的条件是我们使用了eventBus做跨级通信,故vm._hasHookEvent=false
g-popTarget将我们之前push的值remove掉
回到init函数,调用

根据之前分析,将调用beforeCreate函数并在控制台打印输出vue beforeCreate,那么created同样的也是这样一种调用机制
我们先暂停一下,看一下分别在beforeCreate和created之前都做了什么

从两处框红的位置可以看出
框红1的地方,并未对用户暴露出实际可用的接口,所做的操作都是vue内部所使用的方法挂载或者options配置,倒是在框红的2位置,执行了initState方法,该方法对props、methods、data进行了初始化,换句话说,在created后组件的methods、data、props是可用的
继续向后执行$mount方法,在mountComponent中调用beforeMount

可以看出,beforeMount之后紧接着调用了reder和update方法,根据之前的分析,组件在render过程中如果遇到子元素为组件,那么将会构建子组件并在update过程中执行init,而后mount,而后调用beforeMount钩子,如果不存在更多子组件,则结束掉update向下执行父组件的mounted,也就是说,子组件的mounted方法应当在父组件之前
那么,子组件的mounted又是何时被添加、何时被执行的呢?我们知道在patch的最后执行了invokeInsertHook方法,从字面意思理解即"调用插入的hook",代码如下

当父组件vue patch的时候,会先createElm,再createComponent并执行init,子组件的init又再一次patch,也就是子组件patch走到invokeInsertHook的时候parent是有值的,它执行父组件的vnode中保留的占位节点,且由于没有更多的子组件因此不会再次init,所以这里的vnode.parent.data.pendingInsert=[];当子组件patch结束后结束update,并结束子组件init最后回到createComponent,向下调用initComponent

继续向下调用invokeCreateHooks

i存在并且i.insert存在,故将当前的vnode添加进insertedVnodeQueue当中,之后回到父组件的patch过程,再次调用invokeInsertHook。
此时insertedVnodeQueue是有值的即queue是有值的,调用

由于insertedVnodeQueue中保存的是组件vnode,故该处调用的实际是componentVNodeHooks中定义的insert

即组件的mounted调用在此处
此时返回父组件patch过程并结束掉
依次向上返回到mountComponent,调用父组件的mounted

也就是说,我在子组件mounted之后是无法获取父组件的元素的,因为父组件此时还没有执行mounted
那么,befodeUpdate和updated又是哪里执行的呢?
找到Watcher的实例化处

由于这里涉及到响应式的内容,我们在后续章节在深入分析,此时我们只需要找到他的调用处即可
找到src\core\observer\scheduler.js,定位到flushSchedulerQueue函数,找到watcher.before()

在该文件下定位到callUpdatedHooks,找到callHook

最后两个钩子函数是beforeDestory和destoryed,这将在组件的卸载阶段执行,对应原型方法$destroy
如果存在父子引用,则解除引用关系

卸载watcher

卸载事件

组件卸载需要同时卸载子组件,将通过patch方法去递归执行以上几个步骤
