Vue2 and vue3 life cycle changes

Lifecycle hooks in the Vue2 Options API

Each major Vue lifecycle event is split into two hooks that are called before and after that event.


The main four events and eight main hooks are as follows:

  • create - run on the component's creation

  • mount - run when the DOM is mounted

  • update - run after modifying reactive data

  • Destroy - Runs immediately before the element is destroyed.


Vue lifecycle hooks give you the opportunity to run code when Vue performs a specific action on a component. The hooks that Vue exposes for each component include:

  • beforeCreate

  • created

  • beforeMount

  • mounted

  • beforeUpdate

  • updated

  • beforeDestroy

  • destroyed


The above list is ordered. Therefore, Vue always calls beforeCreate before created , and in turn, Vue calls created before beforeMount .


Lifecycle hooks in the Vue3 Composition API


In the Composition API, we have to import lifecycle hooks into our project before we can use them. This is to keep the project as lightweight as possible.


Composition API does not include beforeCreate and created (replaced by the setup method itself), we can access 9 lifecycle hooks in the setup method


onBeforeMount

Called before the mount starts

onMounted

Called when the component is mounted

onBeforeUpdate

Called when responsive data changes and before re-rendering

onUpdated

Called after re-rendering

onBeforeUnmount

在销毁 Vue 实例之前调用

onUnmounted

在实例销毁后调用

onActivated

激活 keep-alive 的组件时调用

onDeactivated

停用 keep-alive 的组件时调用

onErrorCaptured

从子组件捕获错误时调用


Vue2 和 Vue3 的生命周期钩子对比

除了上述介绍和一些命名上的变化,具体用法差不多。Vue3 还新增了用于调试和服务端渲染场景的钩子:

  • onRenderTracked — 调试钩子,响应式依赖被收集时调用

  • onRenderTriggered — 调试钩子,响应式依赖被触发时调用

  • onServerPrefetch — 组件实例在服务器上被渲染前调用

Guess you like

Origin blog.csdn.net/m0_71349739/article/details/128801605