
Vue基础知识:分享"选项式 API 的生命周期选项和组合式API"的应用。
选项式 API 的生命周期选项的变化 {#heading-1}
| Vue2.x | Vue3 | |---------------|-----------------| | beforeCreate | beforeCreate | | created | created | | beforeMount | beforeMount | | mounted | mounted | | beforeUpdate | beforeUpdate | | updated | updated | | beforeDestroy | beforeUnmount | | destroyed | unmounted | | | 新增 | | | errorCaptured | | | renderTracked | | | renderTriggered |
这里我们会发现Vue3对Vue2的生命周期钩子似乎没有做大的调整
-
修改
-
destroyed生命周期选项被重命名为unmounted -
beforeDestroy生命周期选项被重命名为beforeUnmount
-
-
新增
-
errorCaptured:在捕获一个来自后代组件的错误时被调用。
-
renderTracked:跟踪虚拟 DOM 重新渲染时调用。
-
renderTriggered:当虚拟 DOM 重新渲染被触发时调用。
-
{#_lab2_1_0}
小知识 {#heading-2}
所有生命周期钩子的 this 上下文将自动绑定至当前的实例中,所以我们可以在 钩子函数中通过this轻松访问到 data、computed 和 methods。
那么我有个大胆的想法!就是用箭头函数进行定义生命周期钩子函数,可以如期的访问到我们想要的实例吗?
测试:
const app = Vue.createApp({
data() {
return {
cart: 0
}
},
mounted: () => { console.log(this.cart) },
methods: {
addToCart() {
this.cart += 1
}
}
})
app.mount("#app");
不出所望的undefined了,我们打印一下this。

指向的上下文是window并不是我们的Vue实例。
至于为什么会这样,我们可以很简单的从箭头函数的特性来进行一波简单的解释:
我们在定义箭头函数的时候,定义初就绑定了父级上下文,因为箭头函数绑定了父级上下文,所以 this 不会指向预期的组件实例,并且this.data、this.addToCart 都将会是 undefined。
{#_label2}
组合式 生命周期选项 API {#heading-3}
选项式 API 的生命周期选项和组合式 API 之间是有映射关系的, 整体来看,变化不大,只是名字大部分上是on${选项式 API 的生命周期选项}
-
beforeCreate-> 使用setup() -
created-> 使用setup() -
beforeMount->onBeforeMount -
mounted->onMounted -
beforeUpdate->onBeforeUpdate -
updated->onUpdated -
beforeUnmount->onBeforeUnmount -
unmounted->onUnmounted -
errorCaptured->onErrorCaptured -
renderTracked->onRenderTracked -
renderTriggered->onRenderTriggered -
activated->onActivated -
deactivated->onDeactivated
使用:
export default {
setup() {
// mounted
onMounted(() => {
console.log('Component is mounted!')
})
}
}
VNode 生命周期事件 {#heading-4}
在查阅 Vue 的生命周期的时候,发现了这个,说实话我在平常业务开发中还真没怎么用过,不过秉承着宁可多学些也不错过的就记录一下吧!
{#_lab2_3_1}
Vue2x {#heading-5}
在Vue2版本中,如果我们想要监听组件内的生命周期的阶段。我们可以通过 hook:${组件生命周期钩子名称}来进行组件内部的事件监听。
<template>
<child-component @hook:updated="onUpdated">
</template>
或者用驼峰命名法
<template>
<child-component @vnodeUpdated="onUpdated">
</template>
51工具盒子