YouTip LogoYouTip

Vue3 Ref Lifecycle Hooks

Vue 3 Lifecycle Hooks |

\n

Lifecycle 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\n

Registration and Usage of Lifecycle Hooks

\n

mounted hook: This hook is triggered after the component completes its initial rendering and generates DOM nodes. For example:

\n
export default {\n  mounted() {\n    console.log(`Component has been mounted.`);\n  }\n}
\n

Other common hooks: In addition to mounted, there are hooks like updated and unmounted, which are called at different stages of the instance's lifecycle.

\n\n

Precautions for Lifecycle Hooks

\n

this context: The this keyword in all lifecycle hook functions automatically points to the component instance that calls it.

\n

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.

\n

By reasonably utilizing lifecycle hooks, developers can execute specific logic at different stages of a component, enhancing its flexibility and functionality.

\n\n

The following is a diagram of the instance lifecycle:

\nInstance Lifecycle Diagram\n\n

The following are the Vue.js lifecycle hook functions:

\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
Hook NameTrigger Timing
beforeCreateCalled after instance initialization, before data observation and event configuration.
createdCalled immediately after the instance is created. At this point, the instance has finished data observation, property/method computation, and watch/event callbacks.
beforeMountCalled before mounting begins: the related render function is called for the first time.
mountedCalled after the el is replaced by the newly created vm.$el and mounted to the instance.
beforeUpdateCalled when data changes, before the virtual DOM re-renders and patches.
updatedCalled after the virtual DOM re-renders and patches due to data changes.
beforeUnmountCalled before the instance is unmounted.
unmountedCalled after the instance is unmounted.
\n\n

The following provides a detailed introduction to Vue component lifecycle hooks:

\n

Lifecycle 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\n

1. 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
\n

Example:

\n

Example

\n
beforeCreate(){\n console.log('beforeCreate: Instance has just been created');\n}
\n\n

2. 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
\n

Example:

\n

Example

\n
created(){\n console.log('created: Instance creation completed');\n}
\n\n

3. 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
\n

Example:

\n

Example

\n
beforeMount(){\n console.log('beforeMount: Before mounting begins');\n}
\n\n

4. mounted

\n
    \n
  • Description: Called after the el is replaced by the newly created vm.$el and mounted to the instance.
  • \n
  • Usage: You can manipulate the DOM and execute DOM-related logic at this stage.
  • \n
\n

Example:

\n

Example

\n
mounted(){\n console.log('mounted: Instance has been mounted');\n}
\n\n

5. 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
\n

Example:

\n

Example

\n
beforeUpdate(){\n console.log('beforeUpdate: Before data update');\n}
\n\n

6. 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
\n

Example:

\n

Example

\n
updated(){\n console.log('updated: Data update completed');\n}
\n\n

7. 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
\n

Example:

\n

Example

\n
beforeUnmount(){\n console.log('beforeUnmount: Before instance is unmounted');\n}
\n\n

8. 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
\n

Example:

\n

Example

\n
unmounted(){\n console.log('unmounted: Instance has been unmounted');\n}
\n\n

Execution Order of Lifecycle Hooks

\n
    \n
  1. beforeCreate
  2. \n
  3. created
  4. \n
  5. beforeMount
  6. \n
  7. mounted
  8. \n
  9. beforeUpdate (Triggered when data changes)
  10. \n
  11. updated (Triggered when data changes)
  12. \n
  13. beforeUnmount
  14. \n
  15. unmounted
  16. \n
\n\n

Example

\n

The following is a complete Vue component example demonstrating the usage of all lifecycle hook functions:

\n

Example

\n
const 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

Try it Yourself Β»

\n

This example will print logs for each lifecycle hook function in the console, helping to understand the order and purpose of each lifecycle stage.

\nConsole Output Example\n
\n\n

Composition API Hooks

\n

Vue 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
    \n
  • onMounted: Equivalent to mounted.
  • \n
  • onBeforeUnmount: Equivalent to beforeUnmount.
  • \n
  • onUnmounted: Equivalent to unmounted.
  • \n
  • onBeforeMount: Equivalent to beforeMount.
  • \n
  • onBeforeUpdate: Equivalent to beforeUpdate.
  • \n
  • onUpdated: Equivalent to updated.
  • \n
  • onCreated and onBeforeCreate are rarely used in the Composition API, as code in setup runs during the creation phase.
  • \n
\n

Lifecycle hooks using the Composition API:

\n

Example

\n
import{ 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};
\n

Advantages 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
← Mongodb UserCpp Libs Unordered_Map β†’