vue3的声明周期如果是使用选项性Api的话,原来的生命周期钩子可以照常使用,那如果选用vue3组合式Api的话,生命周期需要通过import引入的方式在setup中调用。

<template>
    <div id="test">
        <h3>{{ counter }}</h3>
        <button @click="handleClick">声明周期测试</button>
    </div>
</template>

<script>
import {
    ref,
    onMounted,
    onBeforeMount,
    onBeforeUpdate,
    onUpdated,
    onBeforeUnmount,
    onUnmounted
} from 'vue'
export default {
    setup() {
        const counter = ref(0);
        console.log('....');
        function handleClick() {
            counter.value += 1;
        }
        onBeforeMount(() => {
            console.log("组件挂载之前");
        });
        onMounted(() => {
            console.log("DOM挂载完成");
        });
        onBeforeUpdate(() => {
            console.log("DOM更新之前", document.getElementById("test").innerHTML);
        });
        onUpdated(() => {
            console.log("DOM更新完成", document.getElementById("test").innerHTML);
        });
        onBeforeUnmount(() => {
            console.log("实例卸载之前");
        });
        onUnmounted(() => {
            console.log("实例卸载之后");
        });
        return {
            counter,
            handleClick
        }
    },
}
</script>