Vue-生命周期
Vue-生命周期
钩子函数
有四组(八个)钩子函数,分别在vue的生命周期中被执行
- beforeCreate|created
- beforeMount|mounted
- beforeUpdate|updated
- breforeUnmount|unmounted
在组合式API的生命周期函数中,钩子函数会更改
组合式 API:生命周期钩子 | Vue.js (vuejs.org)
钩子函数的测试
<script setup>
import {ref,onBeforeMount,onMounted,onBeforeUpdate,onUpdated} from 'vue'
//挂载之前
onBeforeMount(()=>{
console.log("----------------------onBeforeMount------------------")
console.log(document.getElementById("s1")) //null
})
//挂载之后
onMounted(()=>{
console.log("----------------------onMounted------------------")
console.log(document.getElementById("s1")) //<span id="s1">1</span>
})
//更新之前
onBeforeUpdate(()=>{
console.log("----------------------onBeforeUpdate------------------")
let ele = document.getElementById("s1")
console.log(message.value,ele.innerText) //2 '1'
})
//更新之后
onUpdated(()=>{
console.log("----------------------onUpdated------------------") //2 '2'
let ele = document.getElementById("s1")
console.log(message.value,ele.innerText)
})
let message = ref(1)
</script>
<template>
<div>
<span id="s1">{{message}}</span>
<button @click="message++">update</button>
</div>
</template>
<style scoped>
</style>