Vue3和Vue2的生命周期差异
Vue组件实例在创建时要经历一系列的初始化步骤,在此过程中Vue会在合适的时机,调用特定的函数,从而会让开发者有机会在特定阶段运行自己的代码,这些特定的函数通称为:生命周期钩子
Vue2的生命周期
<template><div></div>
</template><script>export default{data(){return {}},beforeCreate() {console.log('组件即将创建');},created() {console.log('组件已创建');},beforeMount() {console.log('组件挂载前');},mounted() {console.log('组件已挂载');},beforeUpdate() {console.log('组件更新前');},updated() {console.log('组件已更新');},beforeDestroy() {console.log('组件销毁前');},destroyed() {console.log('组件已销毁');}}
</script>执行顺序依次为:
beforeCreate > created > beforeMount > mounted > beforeUpdate > updated > beforeDestroy > destroyed
当有父子组件时执行顺序
1、父 beforeCreate > 父 created
2、父 beforeMount > 子 beforeCreate > 子 created > 子 beforeMount > 子 mounted > 父 mounted
3、当父组件的某些数据更新时
父 beforeUpdate > 子 beforeUpdate > 子 updated > 父 updated
4、当父组件销毁时
父 beforeDestroy > 子 beforeDestroy > 子 destroyed > 父 destroyed
Vue3的生命周期
<template><div></div><div></div>
</template><script setup >import { onBeforeMount,onMounted,onBeforeUpdate,onUpdated,onBeforeUnMount,onUnMounted } from 'vue'onBeforeMount(()=>{//挂载前})onMounted(()=>{//挂载完毕})onBeforeUpdate(()=>{//更新前})onUpdated(()=>{//更新完毕})onBeforeUnMount(()=>{//卸载前})onUnMounted(()=>{//卸载完毕})
</script>首次加载
父 setup → 父 onBeforeMount → 子 setup → 子 onBeforeMount → 子 onMounted → 父 onMounted
更新
父 onBeforeUpdate → 子 onBeforeUpdate → 子 onUpdated → 父 onUpdated
卸载
父 onBeforeUnmount → 子 onBeforeUnmount → 子 onUnmounted → 父 onUnmounted
