vue生命周期钩子函数

279 阅读1分钟

vue3 组合式API 写法

<template></template>

<script lang='ts'>
// vue3中,生命周期钩子函数需要手动引入
import { defineComponent, onBeforeMount, onMounted, onBeforeUpdate, onUpdated, onBeforeUnmount, onUnmounted} from 'vue';
export default defineComponent({
    setup() {
        // 因为 setup 是围绕 beforeCreate 和 created 生命周期钩子运行的,所以不需要显式地定义它们。
        // 换句话说,在这些钩子中编写的任何代码都应该直接在 setup 函数中编写。
        onBeforeMount(() => {
            console.log('onBeforeMount');
        });
        onMounted(() => {
            console.log('onMounted');
        });
        onBeforeUpdate(() => {
            console.log('onBeforeUpdate');
        });
        onUpdated(() => {
            console.log('onUpdated');
        });
        onBeforeUnmount(() => {
            console.log('onBeforeUnmount');
        });
        onUnmounted(() => {
            console.log('onUnmounted');
        });
        return {};
    },
});
</script>

vue2 选项式API 写法

<template></template>

<script>
export default {
    beforeCreate() {
        console.log("beforeCreate");
    },
    created() {
        console.log("created");
    },
    beforeMount() {
        console.log("beforeMount");
    },
    mounted() {
        console.log("mounted");
    },
    beforeUpdate() {
        console.log("beforeUpdate");
    },
    updated() {
        console.log("updated");
    },
    // vue3版本中,beforeDestroy 更改为 beforeUnmount
    beforeDestroy() {
        console.log("beforeDestroy");
    },
    // vue3版本中,destroyed 更改为 unmounted
    destroyed() {
        console.log("destroyed");
    }
};
</script>