Vue2、Vue3 生命周期的变化
正好在看Vue的官方文档,也正好比对一下,做一下笔记
选项式 API 的生命周期选项的变化
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 重新渲染被触发时调用。
小知识
所有生命周期钩子的 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。
组合式 生命周期选项 API
选项式 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
参考:组合式 API 生命周期钩子
使用:
- export default {
- setup() {
- // mounted
- onMounted(() => {
- console.log('Component is mounted!')
- })
- }
- }
VNode 生命周期事件
在查阅 Vue 的生命周期的时候,发现了这个,说实话我在平常业务开发中还真没怎么用过,不过秉承着宁可多学些也不错过的就记录一下吧!
Vue2x
在Vue2版本中,如果我们想要监听组件内的生命周期的阶段。我们可以通过 hook:${组件生命周期钩子名称}
来进行组件内部的事件监听。
- <template>
- <child-component @hook:updated="onUpdated">
- </template>
Vue3x
在 Vue 3 中,如果我们想要监听组件内的生命周期的阶段。我们可以通过 vnode-${组件生命周期钩子名称}
来进行组件内部的事件监听。额外地,这些事件现在也可用于 HTML 元素,和在组件上的用法一样。
- <template>
- <child-component @vnode-updated="onUpdated">
- </template>
或者用驼峰命名法
- <template>
- <child-component @vnodeUpdated="onUpdated">
- </template>
以上就是一文详解Vue选项式 API 的生命周期选项和组合式API的详细内容,更多关于Vue选项组合API生命周期的资料请关注w3xue其它相关文章!