Every Vue component goes through a series of initialization steps when it is created.
It sets up data observation, compiles the template, mounts the instance to the DOM, and eventually destroys itself.
Vue provides "Lifecycle Hooks", which allow you to execute custom code at these specific stages.
There are several major stages in a Vue component's life.
The most commonly used hooks are:
created(): Called after the instance is created, but before the DOM is rendered.mounted(): Called after the component has been physically inserted into the webpage DOM.updated(): Called whenever reactive data changes and the DOM has been re-rendered.unmounted(): Called when the component is destroyed and removed from the page.The mounted() hook is incredibly popular.
It is the perfect place to fetch data from an API, because you know the HTML is ready for the user to see.
It is also the correct place to initialize any third-party JavaScript libraries (like a map or chart).
export default {
data() {
return { status: 'Loading...' }
},
mounted() {
// This fires immediately when the component hits the screen!
this.status = 'Component is fully mounted!';
console.log('The component is now on the screen.');
}
}
The updated() hook is called after data changes cause the virtual DOM to re-render and patch.
If you need to access the DOM after a state change, this is where you do it.
However, you must be careful not to change the state inside this hook, or you will cause an infinite loop!
export default {
updated() {
console.log('The DOM has just been updated with new data!');
}
}
If you are using the modern <script setup>, the syntax for lifecycle hooks changes slightly.
You must import them from the vue library and prefix them with on.
For example, mounted() becomes onMounted().
Which lifecycle hook is the best place to make an initial API fetch request?
What is a major risk of modifying reactive data inside the updated() hook?