Vue Lifecycle Hooks
Understanding Vue Component Lifecycle:
In Vue. js, every Vue component goes through a chain of events known as the component lifecycle that includes the initialization and destruction phases.
These phases are creation, mounting, updating, and destruction. The component lifecycle is the key to control the component behavior and to perform the tasks at the predefined points in the component's lifecycle.
Using Lifecycle Hooks:
Vue.js has some set of lifecycle hooks, these are like, certain methods that you can define within a vue component to accomplish specific things during the life of the component.
Among these, the most common Lifecycle hooks include created, mounted, updated as well as destroyed. This hooks are used to accomplish jobs like obtaining information, modifying DOM or clearing resources at different life cycle stages of a component.
Example:
<template>
<div>
<p>{{ message }}</p>
</div>
</template>
<script>
export default {
data() {
return {
message: 'Hello, Vue!'
};
},
created() {
console.log('Component created');
// Perform initialization tasks
},
mounted() {
console.log('Component mounted');
// Perform tasks after component is mounted to the DOM
},
updated() {
console.log('Component updated');
// Perform tasks after component is updated
},
destroyed() {
console.log('Component destroyed');
// Perform cleanup tasks before component is destroyed
}
};
</script>
In this example, you have a Vue component having a template that contains a paragraph element displaying a message. We’ve defined lifecycle hooks like created, mounted, updated and destroyed. These hooks will log messages to the console at different stages of the components’ lifecycle.
- created: Created is called synchronously after creating an instance of the component but before it has been mounted on the page. This is where you would usually perform set up operations such as initializing data.
- mounted: Called when the component has just been inserted into DOM. Usually, this is where actions that require access to actual DOM like fetching data from API occur.
- updated: After re-rendering the data of the component and updating the DOM, updated() method is called. At this point within your code may be located actions which need to be done at data changes.
- destroyed: This is invoked just right before we delete an instance of our component from DOM tree structure in order to perform some cleaning up activities like removing event listeners or canceling timers.
With these life-cycle hooks, you can control how your Vue components behave at different points in their lives and ensure correct initialization, manipulation and clean-up tasks.