Vue - An In-Depth Guide to Lifecycle Hooks
Like other frameworks, Vue has many lifecycle hooks that allow us to attach code to specific events that occur when creating or using a Vue application—such as when a component is loaded, when the component is added to the DOM, or when something is removed.
Vue has many lifecycle hooks, and it can be confusing to understand what each hook means or does. In this article, we will introduce the purpose of each lifecycle hook and how to use them.
If you are not familiar with Vue, you can refer to our Vue tutorial.
Vue Lifecycle Hooks
One important point to note here is that Vue has two paradigms for lifecycle hooks. One is the Component API introduced in Vue 3, and the other is the "Options API," which defines Vue components using a prototype pattern. In this article, we will start with the Options API and then demonstrate how the Component API works based on that.
Options API Example
If you're unfamiliar with the Options API, this is what Vue's version looks like in the following code:
export default {
name: 'Component Name',
data() {
return {
phoneNumber: '123-123-123'
}
},
mounted() {
}
}
Running Lifecycle Hooks
To run any lifecycle hook using the Options API, we can add it to the JavaScript prototype. For example, if you want to use beforeCreate()
, the first hook triggered after a new component is detected, you can add it like this:
export default {
name: 'Component Name',
data() {
return {
someData: '123-123-123'
}
},
mounted() {
// Any code that should trigger immediately before the Options API loads
}
}
Now that we have introduced when the different hooks happen, let’s look at what each one does and when they are triggered.
beforeCreate()
Called when the component is initialized. data()
and computed properties are not available at this time. This is useful for calling APIs that do not modify component data. If we update data()
here, it will be lost once the Options API is loaded.
created()
Called after the instance has processed all state operations. We can access reactive data, computed properties, methods, and watchers. $el
is where Vue stores the component's HTML, but it’s not available yet because no DOM elements have been created. If you want to trigger something like an API or update data(), you can do it here.
beforeMount()
This hook runs immediately before the rendering process. The template has been compiled and stored in memory, but it has not yet been attached to the page. No DOM elements have been created. $el is still unavailable at this stage.
This method is not called during server-side rendering.
mounted()
The component is installed and displayed on the page. $el is now available, so we can access and manipulate the DOM from Vue. This will only trigger after all child components have been fully mounted. It’s useful when we want to perform operations on the DOM after it has loaded, like changing specific elements.
This method is not called during server-side rendering.
beforeUpdate()
Sometimes we change the data in a Vue component by updating it in a watcher or through user interaction. When data() changes or triggers a component re-render, the update event is triggered. beforeUpdate() will trigger immediately before the re-render occurs. After this event, the component will re-render and update using the latest data. You can use this hook to access the current state of the DOM and even update data().
This method is not called during server-side rendering.
updated()
Triggered after the update and the DOM has been updated to match the latest data. updated() happens immediately after the re-render. Now, if we access $el or anything related to the DOM content, it will show the new, re-rendered version. If there is a parent component, the child component's updated() is called first, followed by the parent component's updated() hook.
This method is not called during server-side rendering.
beforeUnmount()
If a component is removed, it will be unmounted. beforeUnmount() is triggered before the component is completely deleted. This event still gives you access to the DOM element and any other content related to the component. This is useful for deletion events. For example, you can use this event to notify the server that a user has deleted a node in the table. You can still access this.$el, data, watchers, and methods.
This method is not called during server-side rendering.
unmount()
Triggered after the component is fully deleted. This can be used to clean up other data, event listeners, or timers, letting them know that the component is no longer on the page. You can still access this.$el
, as well as data, watchers, and methods.
This method is not called during server-side rendering.
Using Vue Lifecycle Hooks with the Composition API
If you are used to the Options API, the above hooks will make sense. If you're primarily using Vue 3, you may be more accustomed to using the Composition API. The Composition API is a supplement to the Options API, but the way we use the hooks is a bit different. Let’s take a look at how it works.
created() and beforeCreated() are replaced by setup()
In the Composition API, created() and beforeCreated() are not available. Instead, they are replaced by setup(). This makes sense because there is no "Options API" to load. Any code we would have put in created() or beforeCreated() can now safely go inside setup().
Hooks Can Be Used with setup()
Hooks can still be used with setup(), just like they were in the Options API. This is very intuitive. For example:
export default {
data() {
return {
msg: 1
}
},
setup() {
console.log('Component setup complete')
},
mounted() {
console.log(this.$el)
},
}
However, we may see another way to do this using the Composition API functions to define hooks directly in the setup() function itself. If we do this, the naming of the hooks will be slightly different:
- beforeMount() becomes onBeforeMount()
- mounted() becomes onMounted()
- beforeUpdate() becomes onBeforeUpdate()
- updated() becomes onUpdated()
- beforeUnmount() becomes onBeforeUnmount()
- unmounted() becomes onUnmounted()
These functions work exactly as described in the previous section, but the way they are called is slightly different. All of these hooks must be called inside the setup() function or setup script. For example, we must run the hooks inside the setup() function as shown below:
export default {
setup() {
// All hooks must be placed here
}
}
Alternatively, in a script tag with a setup attribute, as shown below:
<script setup>
// All hooks must be included in this setup script
</script>
So, if we want to call the hooks using this method, the code would look like this:
export default {
setup() {
// All hooks must be placed here
onBeforeMount(() => {
// Code for beforeMount()
});
onBeforeUpdate(() => {
// Code for beforeUpdate()
})
}
}
There is no fundamental performance improvement or better reason. It’s just another way—sometimes, it makes your code easier to read and maintain. In other cases, using the Options API might be better, so use whichever one feels more comfortable for you.
Conclusion
Vue's lifecycle is quite complex, but it provides many tools for running code, updating data, and ensuring that our components display in the way we want. In this article, we’ve introduced how it works, when to use each part of the lifecycle, and how the Composition API differs from the Options API in terms of lifecycle hooks.
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
Webpack packages ES6 and CommonJs mixed React
Publish Date:2025/03/02 Views:179 Category:React
-
This article mainly introduces how to use webpack to package and compile React mixed with ES6 and CommonJs. It is a process of upgrading the React environment.
Details that need to be paid attention to when compiling react with webpack
Publish Date:2025/03/02 Views:199 Category:React
-
It is very convenient to compile and package react using webpack. Both need to be installed using npm. However, if you do not pay attention to the installation location of webpack and react parser babel during use, problems will occur during
How to scroll to the top or bottom of the page in Vue.js
Publish Date:2025/03/01 Views:96 Category:Vue
-
Vue.js is a popular front-end framework that helps developers build efficient and maintainable applications. In Vue.js, scrolling the page to the top or bottom is a common requirement. In this article, we will introduce how to implement this
Display element or text on mouse hover in vue
Publish Date:2025/03/01 Views:179 Category:Vue
-
Vue.js is a popular JavaScript framework that makes web application development easier and more efficient. In this tutorial, we will learn how to use Vue.js to display an element or text on mouse hover. This tutorial will cover the following
When watching an object in Vue, how to exclude certain properties from being watc
Publish Date:2025/03/01 Views:125 Category:Vue
-
When using watch in Vue, you may need to monitor an object, but only care about certain properties in the object, not all properties of the object. In this case, you can use deep monitoring and calculated properties, or add some options to w
What is the use of the immediate property of watch in Vue?
Publish Date:2025/03/01 Views:67 Category:Vue
-
In Vue, watch is a way to perform asynchronous tasks or trigger responsive dependencies when data changes. In most cases, watch will be delayed by default. This means that the watch will only be triggered when the value being monitored chang
Setting up checkbox functionality in Vue
Publish Date:2025/03/01 Views:186 Category:Vue
-
In Vue, checkboxes are a very common interactive component that allows users to select multiple options. This article will introduce how to set up checkbox functionality in Vue and provide some practical examples.
What happens if a child component changes the data in props in Vue?
Publish Date:2025/03/01 Views:140 Category:Vue
-
In Vue, when a child component changes the data in props, it will cause the responsiveness of the parent component and other child components to change. First, you need to understand that props is a way to pass data from a parent component t
How to refresh the page in Vue
Publish Date:2025/03/01 Views:91 Category:Vue
-
Vue is a popular JavaScript framework that provides many convenient tools and methods for building web applications. In Vue, page updates are usually achieved through data binding and responsive systems. But sometimes you need to refresh the