Vue2 生命周期

Vue2 组件的生命周期有 4 个,每个周期对应两个生命周期回调

  • 创建:beforeCreatecreated,只调用一次
  • 挂载:beforeMountmounted,只调用一次
  • 更新:beforeUpdateupdated,每次修改数据都会调用
  • 销毁:beforeDestroydestroyed,只调用一次

Vue3 生命周期

  • 创建:使用 setup 替代了 beforeCreated 和 created,setup 函数的执行在 beforeCreated 函数之前
  • 挂载:onBeforeMountonMounted
  • 更新:onBeforeUpdateonUpdated
  • 销毁:onBeforeUnmountonUnmounted

父组件与子组件的生命周期顺序

  1. 父组件创建
  2. 父组件挂载前
  3. 子组件创建
  4. 子组件挂载
  5. 父组件挂载

自定义 Hooks

将一些可复用的代码封装成一个函数(hook 函数),作为模块使用,hook 文件用 useXXX.ts 命名,存放在 hooks 目录

1
2
3
4
5
6
7
8
9
10
11
12
13
import { ref } from 'vue'
export default function () {
let sum = ref(0)

function add(value: number) {
sum.value += value
}

return {
sum,
add
}
}

在其他模块导入使用

1
2
import useSum from '@/hooks/useSum'
const {sum, add} = useSum()