Vue中的组件生命周期
一个组件从创建到销毁的过程 成为生命周期。
在我们使用Vue3 组合式API 是没有 beforeCreate 和 created 这两个生命周期的
组件生命周期如下:

- onBeforeMount() 在组件DOM实际渲染安装之前调用。在这一步中,根元素还不存在。
- onMounted() 在组件的第一次渲染后调用,该元素现在可用,允许直接DOM访问
- onBeforeUpdate() 数据更新时调用,发生在虚拟 DOM 打补丁之前。
- onUpdated() DOM更新后,updated的方法即会调用。
- onBeforeUnmount() 在卸载组件实例之前调用。在这个阶段,实例仍然是完全正常的。
- onUnmounted() 卸载组件实例后调用。调用此钩子时,组件实例的所有指令都被解除绑定,所有事件侦听器都被移除,所有子组件实例被卸载。
选项API 和组合式API钩子对比
| 选项式API | 组合式API |
|---|---|
| beforeCreate | Not needed* |
| created | Not needed* |
| beforeMount | onBeforeMount |
| mounted | onMounted |
| beforeUpdate | onBeforeUpdate |
| updated | onUpdated |
| beforeUnmount | onBeforeUnmount |
| unmounted | onUnmounted |
| errorCaptured | onErrorCaptured |
| renderTracked | onRenderTracked |
| renderTriggered | onRenderTriggered |
| activated | onActivated |
| deactivated | onDeactivated |
代码示例:
<template><h3>我是组件h3><div ref="div">{{str}}div><button @click="change">修改strbutton>
template>
<script setup lang="ts">
import { ref,onBeforeMount,onMounted,onBeforeUpdate,onUpdated,onBeforeUnmount,onUnmounted } from 'vue';
const str=ref<string>('我是大漂亮');
console.log(str);
const div=ref<HTMLDivElement>();
const change=()=>{str.value='小可爱';
}
onBeforeMount(()=>{console.log('创建前',div.value);
})
onMounted(()=>{console.log('挂载完成',div.value);
})
onBeforeUpdate(()=>{console.log('更新前')
})
onUpdated(()=>{console.log('更新完成')
})
onBeforeUnmount(()=>{console.log('卸载之前')
})
onUnmounted(()=>{console.log('卸载完成')
})
script>
<style scoped>
style>
页面加载完成:
Ref<“我是大漂亮”>
创建前 undefined
挂载完成
<div>小可爱div>"
点击button后:
控制台打印:
更新前
更新完成
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
