你可以通过在生命周期钩子前面加上 “on” 来访问组件的生命周期钩子。
下表包含如何在 setup() 内部调用生命周期钩子:
| 选项式 API | Hook inside setup |
|---|---|
beforeCreate |
Not needed* |
created |
Not needed* |
beforeMount |
onBeforeMount |
mounted |
onMounted |
beforeUpdate |
onBeforeUpdate |
updated |
onUpdated |
beforeUnmount |
onBeforeUnmount |
unmounted |
onUnmounted |
errorCaptured |
onErrorCaptured |
renderTracked |
onRenderTracked |
renderTriggered |
onRenderTriggered |
TIP:因为
setup是围绕beforeCreate和created生命周期钩子运行的,所以不需要显式地定义它们。换句话说,在这些钩子中编写的任何代码都应该直接在setup函数中编写。
这些函数接受一个回调函数,当钩子被组件调用时将会被执行:
1 | // MyBook.vue |
| 生命周期 | 时间节点 |
|---|---|
| setup | 开始创建组件之前,在 beforeCreate 和 created 之间执行;创建的是 data 和 method |
| onBeforeMount | 组件挂载到节点上之前执行 |
| onMounted | 组件挂载完成后执行 |
| onBeforeUpdate | 组件更新之前执行 |
| onUpdated | 组件更新完成之后执行 |
| onBeforeUnmount | 组件卸载之前执行 |
| onUnmounted | 组件卸载完成后执行 |
| onActivated | 被 keep-alive 缓存的组件激活时调用 |
| onDeactivated | 被 keep-alive 缓存的组件失活时调用 |
| onErrorCaptured | 在捕获一个来自后代组件的错误时被调用 |
| onRendeTracked | 跟踪虚拟 DOM 重新渲染时调用 |
| onRenderTriggered | 当虚拟 DOM 重新渲染被触发时调用 |