生命周期
-
vue3取消了vue2里的beforeCreate created, 在setup语法糖模式下是没有这2个生命周期的,使用setup代替
-
onBeforeUpdate读不到dom, onMounted可以读取dom
-
onBeforeUpdate读取的是更新之前的dom,onUpdated读取的是更新之后的dom
-
如果在父组件使用v-if控制本组件的展示与否,那么 v-if从'true'变成'false'时,本组件就会 触发 onBeforeUnmount & onUnmounted 方法 紧接着v-if从'false'变成'true'时,本组件就会 触发 onBeforeMount & onMounted 方法
<template>
<div>
<span ref="sp">{{ str }}</span>
<t-button @click="handleClick">点我就修改</t-button>
<span></span>
</div>
</template>
<script lang="ts">
export default {
name: 'ApplyAWSIndex',
};
</script>
<script setup lang="ts">
import {
ref,
onBeforeMount,
onMounted,
onBeforeUpdate,
onUpdated,
onBeforeUnmount,
onUnmounted,
onRenderTracked,
onRenderTriggered,
} from 'vue';
const str = ref('testt');
const sp = ref<HTMLSpanElement>();
console.log(`setup优先执行`);
const handleClick = () => {
str.value = '我被修改了';
};
onBeforeMount(() => {
console.log(`创建之前==>`, sp.value);
});
onMounted(() => {
console.log(`创建完成==>`, sp.value);
});
onBeforeUpdate(() => {
console.log(`更新之前==>`, sp.value?.innerText);
});
onUpdated(() => {
console.log(`更新之后==>`, sp.value?.innerText);
});
onBeforeUnmount(() => {
console.log(`销毁之前==>`);
});
onUnmounted(() => {
console.log(`销毁之后==>`);
});
// 调试时使用
onRenderTracked((e) => {
console.log(`(调试时使用)收集依赖时:`, e);
});
onRenderTriggered((e) => {
console.log(`(调试时使用)触发更新时:`, e);
});
</script>
<style scoped></style>