每一个.vue
文件都是一个组件,都有自己的生命周期钩子。
组件的生命周期
生产环境可用的10个钩子:
- onBeforeMount 组件被挂载之前调用
- onMounted 组件挂载完成后调用
- onBeforeUpdate 组件即将因为响应式状态变更而更新其 DOM 树之前调用
- onUpdated 组件因为响应式状态变更而更新其 DOM 树之后调用
- onBeforeUnmount 组件实例被卸载之前调用
- onUnmounted 组件实例被卸载之后调用
- onActivated
<KeepAlive>
组件被插入到 DOM 中时调用 - onDeactivated
<KeepAlive>
组件从 DOM 中被移除时调用 - onErrorCaptured 捕获了后代组件传递的错误时调用
- onServerPrefetch 组件实例在服务器上被渲染之前调用(只能在SSR中用)
只能在开发环境中使用的2个钩子:
- onRenderTracked 调试钩子,当组件渲染过程中追踪到响应式依赖时调用
- onRenderTriggered 调试钩子,当响应式依赖的变更触发了组件渲染时调用
父子组件各个阶段生命周期执行顺序
子组件是父组件的一部分,组件运行每个阶段中,父组件执行onBefore[...]
之后,相关子组件执行完对应阶段的钩子onBefore[...]
,on[...]ed
,父组件再执行对应阶段结束钩子on[...]ed
。
其中,使用KeepAlive
包裹的子组件,卸载时只执行onDeactivated
,初始挂载和重新挂载都会执行onActivated
(子组件初始挂载会全部执行一遍挂载的钩子,重新挂载只执行onActivated
)。
对子组件使用KeepAlive
时,子组件的子组件们也会注册和执行相关的onActivated
和onDeactivated
。
挂载阶段(父子组件)
1、挂载父子组件
父组件onBeforeMount —> 子组件onBeforeMount —> 子组件onMounted —> 子组件onActivated(KeepAlive包裹的子组件) —> 父组件onMounted
2、只挂载子组件(🌰:父组件状态条件渲染子组件)
父组件onBeforeUpdate —> 子组件onBeforeMount —> 子组件onMounted —> 父组件onUpdated
3、只重新挂载使用KeepAlive
的子组件
父组件onBeforeUpdate —> 子组件onActivated —> 父组件onUpdated
更新阶段
1、只更新父组件的状态
父组件onBeforeUpdate —> 父组件onUpdated
2、只更新子组件的状态
子组件onBeforeUpdate —> 子组件onUpdated
3、更新了父子组件共用的状态
父组件onBeforeUpdate —> 子组件onBeforeUpdate —> 子组onUpdated —> 父组件onUpdated
子组件卸载阶段(🌰 条件式卸载子组件)
1、卸载不使用KeepAlive
的子组件
父组件onBeforeUpdate —> 子组件onBeforeUnmount —> 子组onUnmounted —> 父组件onUpdated
2、卸载使用了KeepAlive
的子组件
父组件onBeforeUpdate —> 子组件onDeactivated —> 父组件onUpdated
父组件卸载阶段
1、不使用KeepAlive
父组件onBeforeUnmount —> 子组件onBeforeUnmount —> 子组件onUnmounted —> 父组件onUnmounted
2、只子组件用了KeepAlive
父组件onBeforeUnmount —> 子组件onBeforeUnmount —> 子组件onUnmounted —> 子组件onActivated —> 父组件onUnmounted
3、父子组件都用了KeepAlive
子组件onDeactivated —> 父组件 —> onDeactivated