Vue3生命周期函数的那些事

前言

这篇文章给大家介绍关于Vue3中生命周期函数的问题
使用过Vue3的朋友都知道,随着 composition API 的引入,我们在使用钩子函数上也发生了一些改变

Vue3的生命周期函数

下面告诉大家vue2和vue3的生命周期函数改变了哪些:
vue2 —> vue3:

  • beforeCreate -> 不需要
  • created -> 不需要
  • beforeMount -> onBeforeMount
  • mounted -> onMounted
  • beforeUpdate -> onBeforeUpdate
  • updated -> onUpdated
  • beforeUnmount -> onBeforeUnmount
  • unmounted -> onUnmounted
  • errorCaptured -> onErrorCaptured
  • renderTracked -> onRenderTracked
  • renderTriggered -> onRenderTriggered

可以看到在vue3中是没有 beforeCreate 和 created 函数的,这两个函数的方法在vue3里都写在 setup 方法中

生命周期函数的使用

在Vue3中使用生命周期函数需要先进行导入,例如:

import {
    
     onMounted, onUpdated, onRenderTriggered } from 'vue'

导入之后,我们可以在setup()中进行访问

setup() {
    
    
  onMounted(() => {
    
    
    console.log('mounted')
  })
  onUpdated(() => {
    
    
    console.log('updated')
  })
  onRenderTriggered((event) => {
    
    
    console.log(event)
  })
}

最后在Vue3中关于生命周期函数的更多完整内容,可以参考官方文档,帮助大家深入了解 —> 生命周期函数

猜你喜欢

转载自blog.csdn.net/weixin_45745641/article/details/121277663