0
0
Vueframework~5 mins

onUpdated and onBeforeUpdate in Vue

Choose your learning style9 modes available
Introduction

These functions let you run code right before or after a component updates. This helps you react to changes smoothly.

You want to check or change something just before the screen updates.
You need to run code after the component has updated the view.
You want to log or track changes in your component.
You want to perform cleanup or setup related to updates.
You want to trigger animations or effects after updates.
Syntax
Vue
import { onBeforeUpdate, onUpdated } from 'vue';

export default {
  setup() {
    onBeforeUpdate(() => {
      // code to run before update
    });

    onUpdated(() => {
      // code to run after update
    });
  }
}

Use these inside the setup() function of a Vue component.

onBeforeUpdate runs before the DOM updates, onUpdated runs after.

Examples
This logs a message right before the component updates.
Vue
onBeforeUpdate(() => {
  console.log('Component will update soon');
});
This logs a message right after the component updates.
Vue
onUpdated(() => {
  console.log('Component has updated');
});
Use both hooks to manage tasks around updates.
Vue
onBeforeUpdate(() => {
  // Reset a timer or cancel a request before update
});
onUpdated(() => {
  // Start a timer or fetch data after update
});
Sample Program

This component shows a number and a button. When you click the button, the number increases. The console logs the count before and after the update.

Vue
<template>
  <div>
    <p>Count: {{ count }}</p>
    <button @click="increment">Increase</button>
  </div>
</template>

<script setup>
import { ref, onBeforeUpdate, onUpdated } from 'vue';

const count = ref(0);

function increment() {
  count.value++;
}

onBeforeUpdate(() => {
  console.log('Before update: count is', count.value);
});

onUpdated(() => {
  console.log('After update: count is', count.value);
});
</script>
OutputSuccess
Important Notes

These hooks only work inside the setup() function or <script setup>.

They run every time the component updates, so avoid heavy work inside them.

Use console or DevTools to see when these hooks run during development.

Summary

onBeforeUpdate runs just before the component updates the screen.

onUpdated runs right after the screen updates.

Use them to react to changes smoothly and keep your UI in sync.