Vue 3 Lifecycle Hooks |
\nLifecycle hook functions in Vue.js refer to a series of methods automatically called by Vue during the creation, update, and destruction of a component instance. During these steps, the component triggers a series of functions known as "lifecycle hooks," allowing developers to execute custom code at specific moments.
\n\nRegistration and Usage of Lifecycle Hooks
\nmounted hook: This hook is triggered after the component completes its initial rendering and generates DOM nodes. For example:
\nexport default {\n mounted() {\n console.log(`Component has been mounted.`);\n }\n}\nOther common hooks: In addition to mounted, there are hooks like updated and unmounted, which are called at different stages of the instance's lifecycle.
Precautions for Lifecycle Hooks
\nthis context: The this keyword in all lifecycle hook functions automatically points to the component instance that calls it.
Avoid using arrow functions: When defining lifecycle hooks, do not use arrow functions, as this will prevent you from accessing the component instance via this.
By reasonably utilizing lifecycle hooks, developers can execute specific logic at different stages of a component, enhancing its flexibility and functionality.
\n\nThe following is a diagram of the instance lifecycle:
\nThe following are the Vue.js lifecycle hook functions:
\n| Hook Name | \nTrigger Timing | \n
|---|---|
beforeCreate | \n Called after instance initialization, before data observation and event configuration. | \n
created | \n Called immediately after the instance is created. At this point, the instance has finished data observation, property/method computation, and watch/event callbacks. | \n
beforeMount | \n Called before mounting begins: the related render function is called for the first time. | \n
mounted | \n Called after the el is replaced by the newly created vm.$el and mounted to the instance. | \n
beforeUpdate | \n Called when data changes, before the virtual DOM re-renders and patches. | \n
updated | \n Called after the virtual DOM re-renders and patches due to data changes. | \n
beforeUnmount | \n Called before the instance is unmounted. | \n
unmounted | \n Called after the instance is unmounted. | \n
The following provides a detailed introduction to Vue component lifecycle hooks:
\nLifecycle hook functions in Vue.js refer to a series of methods automatically called by Vue during the creation, update, and destruction of a component instance. Through these hooks, specific operations can be performed at different lifecycle stages of the component. Here is a detailed introduction:
\n\n1. beforeCreate
\n- \n
- Description: Instance initialization, called before data observation and event configuration. \n
- Usage: You can initialize some data that is not yet proxied by Vue during this stage. \n
Example:
\nExample
\nbeforeCreate(){\n console.log('beforeCreate: Instance has just been created');\n}\n\n2. created
\n- \n
- Description: Called immediately after the instance is created. At this point, the instance has completed the following configurations: data observation, property/method computation, watch/event callbacks. The mounting phase has not started yet. \n
- Usage: You can access and modify data at this stage, but the DOM has not been mounted yet. \n
Example:
\nExample
\ncreated(){\n console.log('created: Instance creation completed');\n}\n\n3. beforeMount
\n- \n
- Description: Called before mounting begins: the related render function is called for the first time. \n
- Usage: Perform certain operations before mounting, such as modifying the DOM structure. \n
Example:
\nExample
\nbeforeMount(){\n console.log('beforeMount: Before mounting begins');\n}\n\n4. mounted
\n- \n
- Description: Called after the
elis replaced by the newly createdvm.$eland mounted to the instance. \n - Usage: You can manipulate the DOM and execute DOM-related logic at this stage. \n
Example:
\nExample
\nmounted(){\n console.log('mounted: Instance has been mounted');\n}\n\n5. beforeUpdate
\n- \n
- Description: Called when data changes, before the virtual DOM re-renders and patches. \n
- Usage: You can access the state prior to the update during this stage. \n
Example:
\nExample
\nbeforeUpdate(){\n console.log('beforeUpdate: Before data update');\n}\n\n6. updated
\n- \n
- Description: Called after the virtual DOM re-renders and patches due to data changes. \n
- Usage: You can manipulate the DOM at this stage, but avoid changing data during this period as it may cause infinite update loops. \n
Example:
\nExample
\nupdated(){\n console.log('updated: Data update completed');\n}\n\n7. beforeUnmount (Vue 3)
\n- \n
- Description: Called before the instance is unmounted. \n
- Usage: Perform cleanup operations before the instance is unmounted, such as removing event listeners. \n
Example:
\nExample
\nbeforeUnmount(){\n console.log('beforeUnmount: Before instance is unmounted');\n}\n\n8. unmounted (Vue 3)
\n- \n
- Description: Called after the instance is unmounted. \n
- Usage: Perform cleanup operations after the instance is unmounted, such as clearing timers. \n
Example:
\nExample
\nunmounted(){\n console.log('unmounted: Instance has been unmounted');\n}\n\nExecution Order of Lifecycle Hooks
\n- \n
- beforeCreate \n
- created \n
- beforeMount \n
- mounted \n
- beforeUpdate (Triggered when data changes) \n
- updated (Triggered when data changes) \n
- beforeUnmount \n
- unmounted \n
Example
\nThe following is a complete Vue component example demonstrating the usage of all lifecycle hook functions:
\nExample
\nconst LifecycleDemo ={\n template: `{{ message }}`,\n data(){\nreturn{\n message: 'Hello, Vue!'\n};\n},\n beforeCreate(){\n console.log('beforeCreate: Instance has just been created');\n},\n created(){\n console.log('created: Instance creation completed');\n},\n beforeMount(){\n console.log('beforeMount: Before mounting begins');\n},\n mounted(){\n console.log('mounted: Instance has been mounted');\n},\n beforeUpdate(){\n console.log('beforeUpdate: Before data update');\n},\n updated(){\n console.log('updated: Data update completed');\n},\n beforeUnmount(){\n console.log('beforeUnmount: Before instance is unmounted');\n},\n unmounted(){\n console.log('unmounted: Instance has been unmounted');\n}\n};\n\nconst app = Vue.createApp({\n components:{\n LifecycleDemo\n }\n});\n\napp.mount('#app');\n\nThis example will print logs for each lifecycle hook function in the console, helping to understand the order and purpose of each lifecycle stage.
\n\n\n
Composition API Hooks
\nVue 3 introduces the Composition API (Composition API), which allows lifecycle hooks to be organized more logically through the setup function. When using the Composition API, these hooks are defined via onXxx functions:
- \n
onMounted: Equivalent tomounted. \n onBeforeUnmount: Equivalent tobeforeUnmount. \n onUnmounted: Equivalent tounmounted. \n onBeforeMount: Equivalent tobeforeMount. \n onBeforeUpdate: Equivalent tobeforeUpdate. \n onUpdated: Equivalent toupdated. \n onCreatedandonBeforeCreateare rarely used in the Composition API, as code insetupruns during the creation phase. \n
Lifecycle hooks using the Composition API:
\nExample
\nimport{ onMounted, onBeforeUnmount } from 'vue';\n\nexport default{\n setup(){\n onMounted(()=>{\n console.log('Component has been mounted!');\n// Perform initialization operations here\n });\n onBeforeUnmount(()=>{\n console.log('Component is about to be unmounted!');\n// Perform cleanup operations here\n });\n }\n};\nAdvantages of the Composition API:
\n- \n
- High Reusability: Lifecycle hooks can be combined with other logic, making encapsulation and reuse easier. \n
- Clearer Logic: Implemented within the same function as other logic in
setup, reducing code scattering and complexity. \n
YouTip