SoFunction
Updated on 2025-04-11

Learn more about the onMounted and onUnmounted hook functions in Vue 3.0

1. What are onMounted and onUnmounted?

Vue 3.0 brings many exciting new features and improvements, including a more powerful combo API. In this article, we will focus on two important component lifecycle hook functions in Vue 3.0:onMountedandonUnmounted. These two hook functions can help us better manage the life cycle and behavior of components.

onMountedandonUnmountedare two new component lifecycle hook functions in Vue 3.0. They are executed after the component is mounted and before the component is uninstalled. These hook functions can be used to perform some specific logic, such as initializing data, subscribing to events, starting timers, etc.

2. How to use onMounted and onUnmounted?

Let's see how to use these two hook functions in Vue 3.0.

1. Use onMounted

<template>
  <div>
    <h1>{{ message }}</h1>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'

const message = ref('Hello, Vue 3!')

onMounted(() => {
  ('Component mounted')
  // Logic executed after component mount, such as initialization data, subscription events, etc.})
</script>

In the example above, we useonMountedThe hook function executes some logic after the component is mounted, and here it simply prints a message to the console. You can execute any logic in this hook function that needs to be executed immediately after the component is mounted.

2. Use onUnmounted

<script setup>
import { ref, onUnmounted } from 'vue'

const timerId = ref(null)

onUnmounted(() => {
  ('Component will be uninstalled')
  // Logic executed before component uninstallation, such as clearing timer, unsubscribe, etc.  if () {
    clearInterval()
  }
})

const startTimer = () => {
   = setInterval(() => {
    ('Timer is executing')
  }, 1000)
}
</script>

In the example above, we useonUnmountedThe hook function executes some logic before the component is about to be uninstalled, and a timer is cleared here. You can perform any cleaning operations that need to be performed before component uninstallation in this hook function, such as unsubscribe, closing WebSocket connection, etc.

3. Summary

In this article, we learned about Vue 3.0onMountedandonUnmountedHook function and looked at some simple examples. These two hook functions provide us with a more flexible and powerful way of managing component lifecycle, allowing us to better control the behavior of components and the release of resources. I hope this article can help you better understand and apply the combined API in Vue 3.0.

This is the end of this article about the onMounted and onUnmounted hook functions in Vue. For more related contents of onMounted and onUnmounted hook functions in Vue3, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!