Vue2 与 Vue3生命周期对比
1. Vue2.x
2. vu3.x
3. 与 2.x 版本生命周期相对应的组合式 API
beforeCreate
-> 使用setup()
created
-> 使用setup()
beforeMount
->onBeforeMount
mounted
->onMounted
beforeUpdate
->onBeforeUpdate
updated
->onUpdated
beforeDestroy
->onBeforeUnmount
destroyed
->onUnmounted
errorCaptured
->onErrorCaptured
4. 与 2.x 版本生命周期和 3.x 版本执行顺序
<template>
<h1>父组件</h1>
<button @click="isShow = !isShow">切换显示</button>
<hr />
<Child v-if="isShow" />
</template>
<script lang="ts">
import { defineComponent, ref } from "vue";
import Child from "./components/child.vue";
export default defineComponent({
name: "App",
components: {
Child,
},
setup() {
const isShow = ref(true);
return {
isShow,
};
},
});
</script>
<template>
<h1>子组件</h1>
<h2>{{msg}}</h2>
<button @click="updata">更新数据</button>
</template>
<script lang="ts">
import {
defineComponent,
onBeforeMount,
onBeforeUnmount,
onBeforeUpdate,
onMounted,
onUnmounted,
onUpdated,
ref,
} from "vue";
export default defineComponent({
name: "Child",
// vue2.x
beforeCreate() {
console.log("vu2.x - beforeCreate");
},
created() {
console.log("vu2.x - created");
},
beforeMount() {
console.log("vu2.x - beforeMount");
},
mounted() {
console.log("vu2.x - mounted");
},
beforeUpdate() {
console.log("vu2.x - beforeUpdate");
},
updated() {
console.log("vu2.x - updated");
},
// vue3中无法使用 beforeDestroy、destroyed
// beforeDestroy() {
// console.log("vu2.x - beforeDestroy");
// },
// destroyed() {
// console.log("vu2.x - destroyed");
// },
// 修改成 beforeUnmount、unmounted
beforeUnmount() {
console.log("vu2.x - beforeUnmount");
},
unmounted() {
console.log("vu2.x - unmounted");
},
setup() {
console.log("vu3.x - setup");
const msg = ref("abc");
const updata = () => {
msg.value += "--";
};
onBeforeMount(() => {
console.log("vue3.x - onBeforeMount");
});
onMounted(() => {
console.log("vu3.x - onMounted");
});
onBeforeUpdate(() => {
console.log("vu3.x - onBeforeUpdate");
});
onUpdated(() => {
console.log("vu3.x - onUpdated");
});
onBeforeUnmount(() => {
console.log("vu3.x - onBeforeUnmount");
});
onUnmounted(() => {
console.log("vu3.x - onUnmounted");
});
return {
msg,
updata,
};
},
});
</script>