Vue3生命周期了解

111 阅读1分钟

Vue3生命周期

在 setup 中,可以通过 onX 的方式注册 生命周期钩子。

1、beforeCreate -> 使用 setup()

2、created -> 使用 setup()

3、beforeMount -> onBeforeMount

4、mounted -> onMounted

5、beforeUpdate -> onBeforeUpdate

6、updated -> onUpdated

7、beforeDestroy -> onBeforeUnmount

8、destroyed -> onUnmounted

9、errorCaptured -> onErrorCaptured

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vue3生命周期</title>
    <script src="https://unpkg.com/vue@next"></script>
</head>

<body>
    <div id="app">
        <p>{{ state }}</p>
        <button @click='change'>点击改变</button>
    </div>
</body>

</html>
<script>

    const {ref, createApp, reactive, onMounted, onBeforeMount, onBeforeUpdate, onUpdated, onBeforeUnmount, onUnmounted, onErrorCaptured } = Vue

    const App = {
        setup() {
            const state = ref('hello world!')
            onBeforeMount(() => {
                console.log('onBeforeMount: 挂载前')
            })
            onMounted(() => {
                console.log('onMounted: 挂载完成')
            })
            onBeforeUpdate(() => {
                console.log('onBeforeUpdate: 更新前')
            })
            onUpdated(() => {
                console.log('onUpdated: 更新完成')
            })
            const change = function () {
                state.value = "我是love"
            }

            return { state, change }
        }
    }
    Vue.createApp(App).mount('#app')
</script>