生命周期钩子函数
vue3 更新了生命周期钩子函数。
可以直接通过 import 对应的函数(例如:onMounted)来注册生命周期钩子函数。
Options API -> Hook inside setup
beforeCreate-> use setup()created-> use setup()- beforeMount -> onBeforeMount
- mounted -> onMounted
- beforeUpdate -> onBeforeUpdate
- updated -> onUpdated
- beforeUnmount -> onBeforeUnmount
- unmounted -> onUnmounted
- errorCaptured -> onErrorCaptured
- renderTracked -> onRenderTracked(调试用)
- renderTriggered -> onRenderTriggered(调试用)
因为 setup 是在 beforeCreated 和 created 几乎是同时进行的,所以可以将在这两个生命周期里的代码写在 setup 里面。
使用:
import { onMounted, onUpdated, onUnmounted } from 'vue'
const MyComponent = {
setup() {
onMounted(() => {
console.log('mounted!')
})
onUpdated(() => {
console.log('updated!')
})
onUnmounted(() => {
console.log('unmounted!')
})
}
}