vue2 中 执行顺序 :

beforeCreate => created => beforeMount => mounted => beforeUpdate => updated => beforeDestroy => destroyed

vue3 中 执行顺序:

setup => onBeforeMount => onMounted => onBeforeUpdate => onUpdated => onBeforeUnmount => onUnmounted

vue2和vue3生命周期对应关系

vue2 -> vue3

beforeCreate -> setup
created -> setup
beforeMount -> onBeforeMount
mounted -> onMounted
beforeUpdate -> onBeforeUpdate
updated -> onUpdated
beforeDestroy -> onBeforeUnmount
destroyed -> onUnmounted


父子组件执行顺序

挂载阶段

执行顺序为:

父beforeCreate => 父created => 父beforeMount => 子beforeCreate => 子created => 子beforeMount => 子mounted => 父mounted

更新阶段

执行顺序为:

父beforeUpdate => 子beforeUpdate => 子updated => 父updated

销毁阶段

执行顺序为:

父beforeDestroy => 子beforeDestroy => 子destroyed => 父destroyed

规律就是:父组件先开始执行,然后等到子组件执行完,父组件收尾。

不管是哪种情况,都一定是父组件等待子组件完成后,才会执行自己对应完成的钩子

父组件挂载完成一定是等子组件都挂载完成后,才算是父组件挂载完,所以父组件的mounted在子组件mounted之后。

注这个有用在比如,页面跳转,可以在父组件的onBeforeMount进行pinia状态管理的处理,在页面子组件中在进行获取和处理业务。