JIYIK CN >

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

Detailed explanation of Vue life cycle hooks

Author:JIYIK Last Updated:2025/04/20 Views:

Like other frameworks, Vue has a number of lifecycle hooks that allow us to attach code to specific events that occur when creating or using a Vue application — for example, when a component loads, when a component is added to the DOM, or when something is removed.

Vue has a lot of lifecycle hooks, and it can be confusing what each hook means or does. In this article, we'll go over what each lifecycle hook does and how to use them.

If you are not familiar with Vue, you can refer to our Vue tutorial .

Lifecycle hooks in Vue

An important thing to note here is that Vue has two paradigms when it comes to lifecycle hooks. One is using the component API introduced in Vue 3 , and the other is the "Options API", which is a prototype pattern for defining Vue components. In this article, we will start with the Options API and then build on it to show how things work in the component API.

Options API Example

If you’re not familiar with the Options API, that’s Vue’s version and looks like the following:

export default {
    name: 'Component Name',
    data() {
        return {
            phoneNumber: '123-123-123'
        }
    },
    mounted() {

    }
}

Run 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 that is 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() {
        // 在 Options API 加载之前立即触发的任何代码
    }
}

Now that we've covered when the different hooks occur, let's look at what each of them does, and when they fire.

beforeCreate()

Called when the component is initialized. data()Computed properties are not available at this time. It is useful for calling APIs that do not adjust component data. If we update here data(), it will be lost once the Options API is loaded.

created()

Called after the instance has processed all state operations. We can access responsive data, computed properties, methods, and watchers. $elThis is where Vue stores the component HTML, which is not available yet because no DOM elements are created. If you want to trigger something like an API, or update data(), you can do it here.

beforeMount()

This hook runs immediately before rendering occurs. The template has been compiled, so it is stored in memory, but it has not yet been attached to the page. No DOM elements have been created yet. $el is still not available at this stage.

This method is not called when doing server-side rendering of the site.

mounted()

The component is mounted and displayed on the page. $el is now available, so we can now access and manipulate the DOM from Vue. This will only fire after all child components have fully mounted. This is useful when we want to do something with the DOM after it has loaded, like perhaps changing a specific element within it.

This method is not called when doing server-side rendering of the site.

beforeUpdate()

Sometimes we change data in a Vue component, either by updating the data in a watcher or through user interaction. The update event is fired when data() is changed or causes a component to re-render. Before the re-render occurs, beforeUpdate() will fire immediately. After this event, the component will re-render and update with the latest data. You can use this hook to access the current state of the DOM and even update data() from it.

This method is not called when doing server-side rendering of the site.

updated()

After an update is triggered, and the DOM has been updated to match the latest data, updated() will fire. This happens immediately after a re-render. Now, if we access $el or anything else about the DOM content, it will show the new, re-rendered version. If there is a parent component, the child component updated() is called first, followed by the parent component updated() hook.

This method is not called when doing server-side rendering of the site.

beforeUnmount()

If a component is removed, then it is unmounted. beforeUnmount() fires before the component is completely removed. The event still has access to the DOM element and anything else related to the component. This is useful in removal events, for example, you can use this event to notify the server that the user has deleted a node in a table. You still have access to this.$el, as well as data, observers and methods if you need to use them.

This method is not called when doing server-side rendering of the site.

unmount()

Once fully removed, the unmount() event is fired. This can be used to clean up other data or event listeners or timers, letting them know that the component is no longer on the page. We can still access it this.$el, as well as the data, observers, and methods if we need to use them.

This method is not called when doing server-side rendering of the site.

Using Vue lifecycle hooks with the Composition API

If you're used to the Options API, the hooks above will make sense. If you're primarily using Vue 3, you might be more used to the Composition API. The Composition API is a complement to the Options API, but the way we use the hooks is slightly different. Let's take a look at how it works.

created() and beforeCreated() are replaced by setup()

In the combined API, created() and beforeCreated() are not accessible. Instead, they are replaced by setup(). This makes sense, since there is no "Options API" to load. Any code we would have put in created() or beforeCreated() can now be safely put in setup()

Hooks can be used with setup()

Hooks can still be used with setup, just like they do in the Options API, which is pretty intuitive. For example:

export default {
    data() {
        return {
            msg: 1
        }
    },
    setup() {
        console.log('Component setup complete')
    },
    mounted() {
        console.log(this.$el)
    },
}

However, another way we might look at doing this is to use the composition API function to define the hook in the setup() function itself. If we do this, the naming of the hook will be slightly different:

  • beforeMount() becomes onBeforeMount()
  • mount() becomes onMounted()
  • beforeUpdate() becomes onBeforeUpdate()
  • updated() becomes onUpdated()
  • beforeUnmount() becomes onBeforeUnmount()
  • unmounted() becomes onUnmounted()

These functions work exactly the same as described in the previous section, but the way they are called is slightly different. All of these hooks must be called from within a setup() function or a setup script. For example, we must run the hooks from within the setup() function as follows:

export default {
    setup() {
        // 所有的钩子都必须放在这里
    }
}

Or, in a script tag with a setup attribute, like this:

<script setup>
// 所有钩子都必须包含在此设置脚本中
</script>

So if we wanted to call the hook using this method, the code would look like this:

export default {
    setup() {
        // 所有的钩子都必须放在这里
        onBeforeMount(() => {
            // beforeMount() 的代码
        });
        onBeforeUpdate(() => {
            // beforeUpdate() 的代码
        })
    }
}

There's no fundamental performance improvement, and no reason to prefer one over the other. It's just another way to do it - in some cases it'll make your code easier to read and maintain. For other cases it might be better to use the Options API, so use whichever you feel more comfortable with.

Summarize

The Vue lifecycle is fairly complex, but it gives us a lot of tools to run our code, update our data, and make sure our components appear the way we want. In this post, we covered how it works, when to use each part of the lifecycle, and how the Compositions API works differently from the Options API when it comes to 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

Dynamically add properties and values to objects in Vue

Publish Date:2025/04/20 Views:199 Category:Vue

In Vue, we often need to manipulate the properties and values ​​of objects. Sometimes we need to dynamically add properties and values ​​to meet business needs. This article will introduce in detail how to dynamically add properties

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:182 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

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:189 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:141 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

How to find all elements by class name in Vue

Publish Date:2025/03/01 Views:189 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

Scan to Read All Tech Tutorials

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

Recommended

Tags

Scan the Code
Easier Access Tutorial