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
Solution for Flickering During Vue Template Parsing
Publish Date:2025/02/21 Views:103 Category:Vue
-
Solution for Flickering During Vue Template Parsing, Recently, while working on a project, I noticed that when the internet speed is slow, the screen flickers and the expression message appears. This happens because when the internet speed i
使用 JavaScript 通过 XPath 获取元素
Publish Date:2024/03/21 Views:98 Category:JavaScript
-
本教程介绍如何使用 JavaScript Selenium WebDriver 获取元素 XPath。
在 C# 中发出 HTTP POST Web 请求
Publish Date:2024/02/04 Views:131 Category:编程语言
-
在 C# 中,可以使用 3 种主要方法来发出 HTTP POST Web 请求:WebClient 类,HttpWebRequest 类和 HttpClient 类。本教程将讨论在 C# 中发出 HTTP POST Web 请求的方法。使用 C# 中的 WebClient 类发出 HTTP POST Web 请求
Java 中的 WebSocket 客户端
Publish Date:2023/08/09 Views:789 Category:Java
-
本文介绍如何使用 Java 创建 WebSocket 客户端。Java 中的 WebSocket 客户端 WebSocket 可用于在客户端和服务器之间创建通信通道。 WebSocket 协议与用于 Web 通信的 HTTP 兼容。
Java 调用 WebService
Publish Date:2023/07/17 Views:107 Category:Java
-
本文将教我们如何从 Java 类进行 SOAP WebService 调用。SOAP 网络服务 SOAP 代表简单对象访问协议。 可以通过这个基于 XML 的接口来访问 WebService。
在Python中添加Selenium Web Driver等待
Publish Date:2023/07/03 Views:149 Category:Python
-
本文将介绍在Python中在Selenium Web驱动程序中添加等待的示例。Python Selenium Web 驱动程序等待 大多数 Web 应用程序都使用 AJAX 技术。
Python 错误 WebDriverException: Message: Geckodriver Executable Needs to Be in
Publish Date:2023/05/30 Views:252 Category:Python
-
本教程将讨论Python中错误 Message: 'geckodriver' executable needs to be in PATH。geckodriver 是 Mozilla 开发的浏览器引擎,充当 Selenium 和 Firefox 浏览器之间的链接。
Angular CLI Webpack 配置
Publish Date:2023/04/12 Views:284 Category:Angular
-
Angular CLI 提供了用于创建项目、添加和运行测试、生成组件、服务、管道、脚手架模块、特性等的命令。CLI 还提供了一个 webpack 配置文件。
如何在 Vue.js 中滚动到页面顶部或底部
Publish Date:2023/04/03 Views:508 Category:Vue
-
Vue.js 是一种流行的前端框架,它可以帮助开发者构建高效、可维护的应用程序。在Vue.js中,滚动页面到顶部或底部是一个常见的需求。在本文中,我们将介绍如何在Vue.js中实现这一功能