先new Vue 后Vue.component行不行? 不行。
因为new Vue进行选项合并,components也要合并,所以Vue.component必须在new Vue之前使用
初始化是一个递归创建流程
初始化递归创建整棵树时,父子组件的钩子执行顺序是parent.created -> children.created -> children.mounted -> parent.mounted
子组件的挂载流程是在父组件初始化patch过程中执行的
在初始化patch之前,会先调用render获得Vdom,之前说render中组件与tag都是使用_c得到Vdom,在_createElement中,如果是自定义组件,则交由createComponent处理
createComponent有一行installComponentHooks方法非常重要,在生成组件Vdom之前,先安装组件钩子,这与组件的挂载相关,这并不是生命周期钩子。
init钩子是自定组件挂载的起点,将来调用init时,调用createComponentInstanceForVnode -> new vnode.componentOptions.Ctor(options): 调用组件的构造函数返回组件实例,实例调用$mount()执行挂载
const child = vnode.componentInstance = createComponentInstanceForVnode(vnode, activeInstance)
child.$mount(hydrating ? vnode.elm : undefined, hydrating)
在初始化patch流程中:createElm负责为原生tag生成dom插入到父元素中,如果遇到自定义组件的Vdom,则调用组件钩子init()传入父元素执行挂载:
所以children.mounted 在 parent.mounted之前
子组件挂载完成后不能立刻看到画面,需要等待父/根挂载完成后才会出现。