What is onUpdated in Vue: Explanation and Usage
onUpdated is a Vue lifecycle hook that runs after the component’s DOM has been updated due to reactive data changes. It lets you perform actions right after the component re-renders, such as manipulating the DOM or triggering side effects.How It Works
Imagine you have a small machine that changes its display whenever you press a button. The onUpdated hook is like a helper who watches the machine and acts immediately after the display changes. In Vue, when reactive data changes, the component updates its HTML on the page. onUpdated runs right after this update.
This hook is useful because it lets you respond to changes after the screen shows the new state. For example, if you want to adjust something in the DOM that Vue doesn’t handle automatically, you can do it here. It’s like checking your room after cleaning to make sure everything is in place.
Example
This example shows a counter that updates a message after the number changes. The onUpdated hook logs a message every time the component updates.
import { ref, onUpdated } from 'vue'; export default { setup() { const count = ref(0); onUpdated(() => { console.log(`Component updated! Current count is ${count.value}`); }); function increment() { count.value++; } return { count, increment }; }, template: ` <div> <p>Count: {{ count }}</p> <button @click="increment">Increment</button> </div> ` };
When to Use
Use onUpdated when you need to run code right after the component’s HTML changes on the page. This is helpful for:
- Interacting with third-party libraries that need the updated DOM.
- Manually adjusting or measuring DOM elements after updates.
- Triggering animations or side effects that depend on the latest rendered content.
A real-world example is updating a chart or map after data changes, where the library requires the DOM to be ready before drawing.
Key Points
- Runs after DOM updates: It triggers once Vue finishes updating the component’s HTML.
- Not for initial render: It does not run on the first render, only on updates.
- Use carefully: Avoid heavy work here to keep UI responsive.
- Works with reactive data: Runs whenever reactive state changes cause a re-render.
Key Takeaways
onUpdated runs after the component’s DOM updates due to reactive changes.onUpdated to keep the app fast.