Vue2 生命周期
Vue2 组件的生命周期有 4 个,每个周期对应两个生命周期回调
- 创建:
beforeCreate
、created
,只调用一次 - 挂载:
beforeMount
、mounted
,只调用一次 - 更新:
beforeUpdate
、updated
,每次修改数据都会调用 - 销毁:
beforeDestroy
、destroyed
,只调用一次
Vue3 生命周期
- 创建:使用 setup 替代了 beforeCreated 和 created,setup 函数的执行在 beforeCreated 函数之前
- 挂载:
onBeforeMount
、onMounted
- 更新:
onBeforeUpdate
、onUpdated
- 销毁:
onBeforeUnmount
、onUnmounted
父组件与子组件的生命周期顺序
- 父组件创建
- 父组件挂载前
- 子组件创建
- 子组件挂载
- 父组件挂载
自定义 Hooks
将一些可复用的代码封装成一个函数(hook 函数),作为模块使用,hook 文件用 useXXX.ts
命名,存放在 hooks 目录
1 | import { ref } from 'vue' |
在其他模块导入使用
1 | import useSum from '@/hooks/useSum' |