正好在看Vue的官方文档,也正好比对一下,做一下笔记
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
所有生命周期钩子的 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 之间是有映射关系的, 整体来看,变化不大,只是名字大部分上是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!') }) } } 复制代码
在查阅 Vue 的生命周期的时候,发现了这个,说实话我在平常业务开发中还真没怎么用过,不过秉承着宁可多学些也不错过的就记录一下吧!
在Vue2版本中,如果我们想要监听组件内的生命周期的阶段。我们可以通过 hook:${组件生命周期钩子名称}
来进行组件内部的事件监听。
<template> <child-component @hook:updated="onUpdated"> </template> 复制代码
在 Vue 3 中,如果我们想要监听组件内的生命周期的阶段。我们可以通过 vnode-${组件生命周期钩子名称}
来进行组件内部的事件监听。额外地,这些事件现在也可用于 HTML 元素,和在组件上的用法一样。
<template> <child-component @vnode-updated="onUpdated"> </template> 复制代码
或者用驼峰命名法
<template> <child-component @vnodeUpdated="onUpdated"> </template>
如果你觉得此文对你有一丁点帮助,点个赞。或者可以加入我的开发交流群:1025263163相互学习,我们会有专业的技术答疑解惑
如果你觉得这篇文章对你有点用的话,麻烦请给我们的开源项目点点star:http://github.crmeb.net/u/defu不胜感激 !
完整源码下载地址:https://market.cloud.tencent.com/products/33396
PHP学习手册:https://doc.crmeb.com
技术交流论坛:https://q.crmeb.com
|