选项式API下的生命周期函数使用 | 组合式API下的生命周期函数使用 |
---|---|
beforeCreate | 不需要(直接写到setup函数中) |
created | 不需要(直接写到setup函数中) |
beforeMount | onBeforeMount |
mounted | onMounted |
beforeUpdate | onBeforeUpdate |
updated | onUpdated |
beforeDestroyed | onBeforeUnmount |
destroyed | onUnmounted |
生命周期钩子函数使用场景
生命周期钩子函数 | 应用场景 |
---|---|
created | 发送ajax请求 / 挂载共用属性 |
mounted | 发送ajax请求 / 依赖于dom的业务,比如地图,图表 |
destroyed | 销毁操作,比如定时器 |
代码演示如下:
<template>
<div>生命周期函数</div>
</template>
<script>
import { onMounted } from 'vue'
export default {
setup() {
// 时机成熟 回调函数自动执行
onMounted(() => {
console.log('mouted生命周期执行了')
})
onMounted(() => {
console.log('mouted生命周期函数又执行了')
})
}
}
</script>