Vue3生命周期依次顺序:
setup
等同于beforeCreate和created阶段。
onBeforeMount
在Dom挂载到页面之前
onMounted
在Dom挂载到页面之后
onBeforeUpdate
在参与页面渲染的数据更新之前 PS:参与页面数据渲染指的是即使该数据改变后没有改变页面显示,但是它参与了组件的属性传值,这种也会触发此生命周期的调用。
onUpdated
在参与页面渲染的数据更新之后 PS:参与页面数据渲染指的是即使该数据改变后没有改变页面显示,但是它参与了组件的属性传值,这种也会触发此生命周期的调用。
onBeforeUnmount
在页面销毁之前
onUnmounted
在页面销毁之后
以下是调试代码:
子组件
<template>
<p>生命周期 {{ msg }}</p>
</template>
<script setup>
import {
onBeforeMount,
onMounted,
onBeforeUpdate,
onUpdated,
onBeforeUnmount,
onUnmounted,
} from "vue";
const props = defineProps({
msg: {
type: String,
},
});
onBeforeMount(() => {
console.log("onBeforeMount");
});
onMounted(() => {
console.log("onMounted");
});
onBeforeUpdate(() => {
console.log("onBeforeUpdate");
});
onUpdated(() => {
console.log("onUpdated");
});
onBeforeUnmount(() => {
console.log("onBeforeUnmount");
});
onUnmounted(() => {
console.log("onUnmounted");
});
</script>
<style lang="scss" scoped></style>
父组件
<template>
<LifeCycle :msg="msgRef" v-if="flagRef" />
<button @click="changeHandler">change msg</button>
<button @click="changeFlagHandler">change flag</button>
</template>
<script setup>
import LifeCycle from "./components/lifeCycle.vue";
import { ref } from "vue";
const msgRef = ref("hello");
const flagRef = ref(true);
function changeHandler() {
msgRef.value='hello world';
}
function changeFlagHandler() {
flagRef.value = !flagRef.value;
}
</script>
<style scoped></style>