生命周期
Vue组件在创建时要经历一系列的初始化步骤,在此过程中Vue会在合适的时机,调用特定的函数,从而让开发者有机会在特定阶段运行自己的代码,这些特定的函数统称为:生命周期钩子
Vue2
在Vue2中,组件的生命周期分为四个阶段,八个钩子函数
创建
创建前 beforeCreate
创建完 created
挂载
挂载前 beforeMount
挂载完 mounted
更新
更新前 beforeUpdate
更新完 updated
销毁
销毁前 beforeDestory
销毁完 destoryed
Vue3
在Vue3中,钩子函数有7个,创建只有一个
创建
创建 setup
挂载
挂载前 onBeforeMount
挂载完 onMounted
更新
更新前 onBeforeUpdate
更新完 onUpdated
卸载
卸载前 onBeforeunmount
卸载完 onUnmounted
<script lang="ts" setup name="text2">import {onBeforeMount,onMounted,onBeforeUpdate,onUpdated,onBeforeunmount,onUnmounted } from 'vue'// 创建console.log('创建');// 挂载前onBeforeMount(()=>{console.log('挂载前');})// 挂载完成onMounted(()=>{console.log('挂载完成');})// 更新前onBeforeUpdate(()=>{console.log('更新前');})// 更新完成onUpdated(()=>{console.log('更新完成');})// 卸载前onBeforeunmount(()=>{console.log('卸载前');})// 卸载完成onUnmounted(()=>{console.log('卸载完成');})</script>
在Vue3中使用钩子函数需要 import 引入
子组件的挂载要先于父组件,因为深度优先
第四个阶段在Vue3内叫卸载,且函数变化