此系列文章合集click me
此系列文章源码click me
对比表
Vue2 | 对比 | Vue3 | 执行阶段 |
---|---|---|---|
beforeCreate | ==> | setup() | |
created | ==> | setup() | 组件创建之前 |
beforeMount | ==> | onBeforeMount | 组件挂载到节点之前 |
mounted | ==> | onMounted | 组件挂载完成后 |
beforeUpdate | ==> | onBeforeUpdate | 组件更新之前 |
updated | ==> | onUpdated | 组件更新完成之后 |
beforeDestroy | ==> | onBeforeUnmount | 组件卸载之前 |
destroyed | ==> | onUnmounted | 组件卸载完成 |
activated | ==> | onActivated | 进入缓存组件时 |
deactivated | ==> | onDeactivated | 离开缓存组件时 |
errorCaptured | ==> | onErrorCaptured | 当子孙组件出错时 |
新增 | onRenderTriggered | 跟踪虚拟 DOM 重新渲染时调用 | |
新增 | onRenderTracked | 当虚拟 DOM 重新渲染被触发时调用 |
lifeCycle.vue
<template>
<div id="app">
<h2>msg: {{ msg }}</h2>
<button @click="updateMsg">更新msg</button>
<button @click="goKeepAliveCom">前往缓存组件</button>
</div>
</template>
<script lang="ts">
import {
ref,
defineComponent,
onBeforeMount,
onBeforeUnmount,
onBeforeUpdate,
onMounted,
onUnmounted,
onUpdated,
} from "vue";
import { useRouter } from "vue-router";
export default defineComponent({
setup() {
const msg = ref("温情");
const updateMsg = () => {
msg.value += "K";
};
const router = useRouter();
const goKeepAliveCom = () => {
router.push('/keepAlive');
}
onBeforeMount(() => {
console.log("onBeforeMount-组件挂载到节点之前");
});
onMounted(() => {
console.log("onMounted-组件挂载完成后");
});
onBeforeUpdate(() => {
console.log("onBeforeUpdate-组件更新之前");
});
onUpdated(() => {
console.log("onUpdated-组件更新完成之后");
});
onBeforeUnmount(() => {
console.log("onBeforeUnmount-组件卸载之前");
});
onUnmounted(() => {
console.log("onUnmounted-组件卸载完成");
});
console.log("setup-开始创建组件之前");
return {
msg,
updateMsg,
goKeepAliveCom
};
},
});
</script>
keep-alive.vue
<template>
<div id="app">
<input type="text" v-model="ipt" />
<br />
<button @click="router.back()">返回</button>
</div>
</template>
<script lang="ts">
import { defineComponent, onActivated, onDeactivated, onMounted, ref } from "vue";
import { useRouter } from "vue-router";
export default defineComponent({
setup() {
const ipt = ref("");
const router = useRouter();
onMounted(() => {
console.warn("只有第一次进入缓存组件才触发onMounted")
})
onActivated(() => {
console.log("进入缓存组件onActivated");
});
onDeactivated(() => {
console.log("离开缓存组件onDeactivated");
});
return { ipt, router };
},
});
</script>
由于输出的实在太多,截图不便于理解,所以建议自己动手试试。