3、Vue3的生命周期和钩子函数

1,201 阅读3分钟

Vue3 版本的生命周期和 Vue2 比有些许变化

以下为Vue3版本生命周期:

  • setup() :开始创建组件之前,在beforeCreatecreated之前执行。创建的是datamethod
  • onBeforeMount() : 组件挂载到节点上之前执行的函数。
  • onMounted() : 组件挂载完成后执行的函数。
  • onBeforeUpdate(): 组件更新之前执行的函数。
  • onUpdated(): 组件更新完成之后执行的函数。
  • onBeforeUnmount(): 组件卸载之前执行的函数。
  • onUnmounted(): 组件卸载完成后执行的函数
  • onActivated(): 被包含在<keep-alive>中的组件,会多出两个生命周期钩子函数。被激活时执行。
  • onDeactivated(): 比如从 A 组件,切换到 B 组件,A 组件消失时执行。
  • onErrorCaptured(): 当捕获一个来自子孙组件的异常时激活钩子函数(以后用到再讲,不好展现)。

注:使用<keep-alive>组件会将数据保留在内存中,比如我们不想每次看到一个页面都重新加载数据,就可以使用<keep-alive>组件解决。

Vue3生命周期在调用前需要先进行引入,如下:

import {
  reactive,
  toRefs,
  onMounted,
  onBeforeMount,
} from "vue";

注:Vue3中,钩子函数写在setup()中。

同样,vue2的生命周期也可在vue3版本中使用,只不过钩子函数与setup同级使用,对比之下,建议在vue3中使用vue3的生命周期和钩子函数,不要进行混用。

Vue2.x 和 Vue3.x 生命周期对比


Vue2--------------vue3
beforeCreate  -> setup()
created       -> setup()
beforeMount   -> onBeforeMount
mounted       -> onMounted
beforeUpdate  -> onBeforeUpdate
updated       -> onUpdated
beforeDestroy -> onBeforeUnmount
destroyed     -> onUnmounted
activated     -> onActivated
deactivated   -> onDeactivated
errorCaptured -> onErrorCaptured

通过这样对比,可以很容易的看出 vue3 的钩子函数基本是再 vue2 的基础上加了一个on,但也有两个钩子函数发生了变化。

  • BeforeDestroy变成了onBeforeUnmount
  • destroyed变成了onUnmounted

尤大神的介绍是mountDestroy更形象,也和beforeMount相对应。

新增 onRenderTracked()和 onRenderTriggered()

onRenderTracked()

这两个钩子函数是Vue3版本新增的两个钩子函数,官方说是用来调试使用的。

onRenderTracked直译过来就是状态跟踪,它会跟踪页面上所有响应式变量和方法的状态,也就是我们用return返回去的值,他都会跟踪。只要页面有update的情况,他就会跟踪,然后生成一个event对象,我们通过event对象来查找程序的问题所在。

使用onRenderTracked同样要使用import进行引入。

import { .... ,onRenderTracked,} from "vue";

引用后就可以在setup()函数中进行引用了。

onRenderTracked((event) => {
  console.log("状态跟踪组件----------->");
  console.log(event);
});

image.png

onRenderTriggered()

onRenderTriggered直译过来是状态触发,它不会跟踪每一个值,而是给你变化值的信息,并且新值和旧值都会给你明确的展示出来。 与watch相似。

使用它同样要先用import进行引入

import { .... ,onRenderTriggered,} from "vue";

在使用onRenderTriggered前,记得注释相应的onRenderTracked代码,这样看起来会直观很多。 然后把onRenderTriggered()函数,写在setup()函数里边,

onRenderTriggered((event) => {
  console.log("状态触发组件--------------->");
  console.log(event);
});

对 event 对象属性的详细介绍:

- key 那边变量发生了变化
- newValue 更新后变量的值
- oldValue 更新前变量的值
- target 目前页面中的响应变量和函数

image.png

学习日期:2022/1/12

视频参考www.bilibili.com/video/BV1L5…

文档参考jspang.com/detailed?id…

仅供个人学习和记录