JIYIK CN >

Current Location:Home > Learning > WEB FRONT-END > Vue >

Vue - An In-Depth Guide to Lifecycle Hooks

Author:JIYIK Last Updated:2025/02/21 Views:

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.

Article URL:

Related Articles

Configuring Apache Web Server on Ubuntu and Debian

Publish Date:2025/04/05 Views:176 Category:OPERATING SYSTEM

This article shows you how to install Apache web server on Ubuntu and Debian, set it up, and access the access logs. Apache Web Server in Ubuntu and Debian Apache HTTP Server is a free and open source web server that is very popular. More t

How to use Docker to image a Node.js web application

Publish Date:2025/03/26 Views:107 Category:Docker

Docker is a containerization platform that simplifies the packaging and execution of applications. Containers run as independent processes with their own file systems, but share the kernel of their host machine. Docker has attracted much at

My understanding of webservice is this

Publish Date:2025/03/18 Views:150 Category:NETWORK

Recently, I encountered such a project at work (temporarily named Project A). Project A itself was developed in PHP, but its data came from another project developed in Java (temporarily named Project B). Project A could not operate the dat

Which technology do you choose to implement the web chat room?

Publish Date:2025/03/18 Views:62 Category:NETWORK

With the rise of HTML5 Websockets, web chat applications are becoming more and more popular. Recently, I am working on a mobile web application, the core function of which is to implement web chat on the mobile phone. Of course, the functio

How to redirect a website from HTTP to HTTPS

Publish Date:2025/03/16 Views:117 Category:NETWORK

HTTPS is a protocol for secure communication over computer networks and is widely used on the Internet. More and more website owners are migrating from HTTP to HTTPS, mainly due to the following 5 reasons: Google announced that websites usi

How to avoid soft 404 in the website during SEO

Publish Date:2025/03/17 Views:136 Category:NETWORK

This article shares an SEO problem, soft 404. A status code we often see on websites is 404. Whether we develop a website or not, this is a problem we have to face. What is a soft 404? Before talking about soft 404, we must first understand

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.

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial