+
95
-

回答

vue3要想使用onMounted函数,必须import一下,代码如下:

import { onMounted, onUpdated, onUnmounted } from 'vue'

除了 beforeCreate 和 created 之外,在我们的Vue3的 setup 方法中,有9个旧的生命周期钩子,我们可以在setup 方法中访问

onBeforeMount
onMounted
onBeforeUpdate
onUpdated
onBeforeUnmount
onUnmounted
onActivated
onDeactivated
onErrorCaptured

我们导入它们并在我们的代码中访问它们

import { onBeforeMount, onMounted, onBeforeUpdate, onUpdated, onBeforeUnmount, onUnmounted, onActivated, onDeactivated, onErrorCaptured } from 'vue'

export default {
setup() {
onBeforeMount(() => {
// ...
})
onMounted(() => {
// ...
})
onBeforeUpdate(() => {
// ...
})
onUpdated(() => {
// ...
})
onBeforeUnmount(() => {
// ...
})
onUnmounted(() => {
// ...
})
onActivated(() => {
// ...
})
onDeactivated(() => {
// ...
})
onErrorCaptured(() => {
// ...
})
}
}


从Vue2转换到Vue3钩子函数的变化

beforeCreate -> use setup()
created -> use setup()
beforeMount -> onBeforeMount
mounted -> onMounted
beforeUpdate -> onBeforeUpdate
updated -> onUpdated
beforeDestroy -> onBeforeUnmount
destroyed -> onUnmounted
errorCaptured -> onErrorCaptured

新的调试钩子函数

们还可以在Vue3中使用两个全新的钩子函数来进行调试。他们是:

onRenderTracked

onRenderTriggered

这两个事件都带有一个DebuggerEvent,它使我们能够知道是什么导致了Vue实例中的重新渲染。

export default {
onRenderTriggered(e) {
debugger
// 检查哪个依赖项导致组件重新呈现
}
}


网友回复

我知道答案,我要回答