Vue3 中的生命周期

2,110 阅读1分钟

Vue3 中的生命周期

什么是生命周期

组件从创建到销毁的整个过程,不同阶段执行不同的函数

组件初始化

beforeCreated --> created --> beformount --> mounted

特点:在组件初始化的过程中执行一次

响应式数据更新时

beforeUpdate --> updated

特点:只要响应式数据发生变化引起了组件渲染,两个函数就会不断执行

组件销毁

vm.$destory() breforeDestory --> destroyed

特点:只会执行一次

常见的钩子函数

  • created 发送 ajax
  • mounted 发送 ajax + dom echart图表 地图业务
  • destroyed 清除内存操作 清理定时器

vue3中使用步骤

  • 先从 vue 中导入以 on打头 的生命周期钩子函数
  • setup 函数中调用生命周期函数并传入回调函数
  • 生命周期钩子函数可以调用多次

代码演示

<template>
  <div>生命周期函数</div>
</template>

<script>
import { onMounted } from 'vue'
export default {
  setup() {
    // 时机成熟 回调函数自动执行
    onMounted(() => {
      console.log('mouted生命周期执行了')
    })
    onMounted(() => {
      console.log('mouted生命周期函数又执行了')
    })
  }
}
</script> 
选项式API下的生命周期函数使用组合式API下的生命周期函数使用
beforeCreate不需要(直接写到setup函数中)
created不需要(直接写到setup函数中)
beforeMountonBeforeMount
mountedonMounted
beforeUpdateonBeforeUpdate
updatedonUpdated
beforeDestroyedonBeforeUnmount
destroyedonUnmounted