Vue.js life cycle
What is life cycle?
The life cycle refers to the entire process of a Vue component from creation to destruction. In this process, Vue provides a series of hook functions that allow us to execute code at specific stages.
Vue 3 life cycle hook
Composite API life cycle hooks
In Vue 3<script setup>, lifecycle hooks need to be imported from Vue:
Life cycle diagram
Detailed explanation of each life cycle hook
onMounted (after mounting)
Called after the component is mounted to the DOM, DOM elements can be accessed at this time.
onBeforeMount (before mounting)
Called before the component is mounted to the DOM.
onUpdated (after update)
Called after responsive data changes cause the DOM to update.
onBeforeUpdate (before update)
Called after the responsive data changes and before the DOM is updated.
onUnmounted (after unmounting)
Called after the component is uninstalled for cleanup work.
onBeforeUnmount (before unmounting)
Called before the component is uninstalled.
Practical example: data loading
Practical example: timer
Practical example: event monitoring
Practical example: third-party library integration
Life cycle best practices
1. Perform DOM operations in onMounted
2. Clean up side effects
3. Avoid modifying status in onUpdated
4. Use combined functions to encapsulate life cycle logic
Optional API vs Composite API
Option API (Vue 2 style)
Composite API (Vue 3 recommended)
Summarize
- onMounted: After the component is mounted, it is suitable for DOM operations, API requests, and initialization of third-party libraries
- onUnmounted: After the component is uninstalled, it is suitable for cleaning up timers, event monitoring, and canceling requests.
- onUpdated: After the data is updated, avoid modifying the status here
- setup(): equivalent to beforeCreate and created
- Use combined functions to encapsulate reusable life cycle logic
- Always remember to clean up side effects to avoid memory leaks
Next step
Next, learn Dynamic Components to learn how to dynamically switch components.