
Vue基础知识:分享“选项式 API 的生命周期选项和组合式API”的应用。
选项式 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生命周期选项被重命名为unmountedbeforeDestroy生命周期选项被重命名为beforeUnmount新增
小知识
所有生命周期钩子的 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。

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


网友评论文明上网理性发言 已有0人参与
发表评论: