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:
<scriptsetup>// all hooks must be included in this setup scriptscript>
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.
article url:
related articles
what is the use of the immediate property of watch in vue?
publish date:2025/03/01 views:65 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:185 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:138 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:85 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
how to find all elements by class name in vue
publish date:2025/03/01 views:182 category:vue
-
vue is a very powerful javascript framework that provides developers with a lot of convenient features and tools. one of them is finding all elements by class name. in this article, we will explore how to find all elements by class name in
when calculating variables in vue, which is better, methods or computed?
publish date:2025/03/01 views:110 category:vue
-
when calculating variables in vue, we usually use two methods: methods and computed. although both can be used to calculate variables, there are still some differences in their use. this article will introduce in detail the differences betwe
how to get the initial state of a certain data in vue?
publish date:2025/03/01 views:146 category:vue
-
in vue, sometimes we want to get the initial state of a data in data so that we can compare or reset it in subsequent operations. in this article, we will introduce how to get the initial state of a data in data and provide an example to il
implementation of scheduling execution in vue project
publish date:2025/03/01 views:128 category:vue
-
in vue projects, scheduling execution refers to assigning tasks to different components or instances to implement functions such as data processing, rendering, and interaction. this article will introduce the implementation method of schedul
defining global components in vue
publish date:2025/03/01 views:99 category:vue
-
in vue, global components are a very important concept that allows us to use the same components everywhere. in this article, we will discuss how to define global components in vue and the relevant precautions.