Vue2和Vue3中的生命周期钩子函数非常相似——我们仍然可以访问相同的钩子函数,并且我们仍然希望将它们用于相同的用例。
但是,随着Composition API的引入,我们访问这些钩子函数的方式已经改变。
到本文结束时,你将了解在Vue3中使用生命周期钩子函数的新方法,并开始编写更好的代码。
什么是Composition API
如果你还不知道,Vue3 Composition API 附带了一个 setup() 方法。此方法封装了我们的大多数组件代码,并处理了响应式,生命周期钩子函数等。
简而言之,Composition API使我们能够更好地将代码组织为更多的模块化功能,而不是根据属性的类型(方法,计算的数据)进行分离。
在旧的 beforeCreate 钩子函数之后和 created 的钩子函数之前立即调用 setup 方法。因此,我们不再需要这两个钩子,我们可以简单地将本应有的代码放在 setup() 方法中。
添加我们的生命周期钩子
与Vue3中的大多数功能一样,生命周期钩子是我们必须导入到项目中的东西,这是为了帮助使项目尽可能轻巧。
我们导入生命周期钩子的方式是这样的。
import { onMounted, onUpdated, onUnmounted } from 'vue'
除去 beforeCreate 和 created 之外,在我们的 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
这个方便的Vue2到Vue3的生命周期映射直接来自于Vue3 Composition API 文档,我认为这是一种最有用的方式来查看事情将如何变化,以及我们如何使用它们。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
// 检查哪个依赖项导致组件重新呈现 }
}
就是这样!
如果你已经有Vue的经验,那么这将是一个非常容易的切换,只需导入钩子并将它们包括在 setup 方法中即可。
我希望这可以帮助你更多地了解Vue3中的更改以及如何在项目中实现它们。