生命周期函数代表的是Vue
实例,或者是Vue
组件,在网页中各个生命阶段所执行的函数。生命周期函数可以分为创建阶段、挂载阶段、更新阶段以及卸载阶段。
setup
onBeforeMount
、onMounted
onBeforeUpdate
、onUpdated
onBeforeUnmount
、onUnmounted
<template>
<h2>count为:{{ count }}</h2>
<button @click="onUpdateCount">更新count</button>
</template>
<script setup>
import {
ref,
onBeforeMount,
onMounted,
onBeforeUpdate,
onUpdated,
onBeforeUnmount,
onUnmounted
} from 'vue'
// 数据
let count = ref(0)
// 方法
function onUpdateCount() {
count.value += 1
}
console.log('setup')
// 生命周期钩子
onBeforeMount(() => {
console.log('挂载之前')
})
onMounted(() => {
console.log('挂载完毕')
})
onBeforeUpdate(() => {
console.log('更新之前')
})
onUpdated(() => {
console.log('更新完毕')
})
onBeforeUnmount(() => {
console.log('卸载之前')
})
onUnmounted(() => {
console.log('卸载完毕')
})
</script>