文章目录
前言
每个 Vue 组件实例在创建时都需要经历一系列的初始化步骤,比如设置好数据侦听,编译模板,挂载实例到 DOM,以及在数据改变时更新 DOM。在此过程中,它也会运行被称为生命周期钩子的函数,让开发者有机会在特定阶段运行自己的代码。
一、生命周期
1. 两大类
- 选项式 API
- 组合式 API
两类生命周期用法不同,作用是一样的。
2. 生命周期
-
beforeCreate
-
created
-
beforeMount
-
mounted
-
beforeUpdate
-
updated
-
beforeUnmount
-
unmounted
二、选项式生命周期
1. 代码
<!-- 选项式 API -->
<script>
export default {
data() {
return {
msg: '北京',
count: 0
};
},
beforeCreate() {
console.log('the component is now before create.')
},
created() {
console.log('the component is now created.')
},
beforeMount() {
console.log('the component is now before mount.')
},
mounted() {
console.log('the component is now mounted.')
},
beforeUpdate() {
console.log('the component is now before update.')
},
updated() {
console.log('the component is now updated.')
},
beforeUnmount() {
console.log('the component is now before unmount.')
},
unmounted() {
console.log('the component is now unmounted.')
}
};
</script>
<template>
<h2>{{ msg }},欢迎你</h2><br>
<button id="count" @click="count++">{{ count }}</button>
</template>
<style>
h2{
color:red;
}
</style>
2. 效果
三、组合式生命周期
1. 代码
<script setup>
import { ref,onBeforeMount,onMounted,onBeforeUpdate, onUpdated,onBeforeUnmount,onUnmounted } from 'vue'
const msg=ref('北京')
onBeforeMount(() => {
console.log(`the component is now before mounted.`)
})
onMounted(() => {
console.log(`the component is now mounted.`)
})
const count = ref(0)
onBeforeUpdate(() => {
console.log(`the component is now before updated.`)
})
onUpdated(() => {
console.log(`the component is now updated.`)
})
onBeforeUnmount(() => {
console.log(`the component is now before unmount.`)
})
onUnmounted(() => {
console.log(`the component is now unmounted.`)
})
</script>
<template>
<h1>{{ msg }},欢迎你</h1><br>
<button id="count" @click="count++">{{ count }}</button>
</template>
<style>
h1{
color:red;
}
</style>