0
0
Vueframework~3 mins

Why Directive hooks (mounted, updated, unmounted) in Vue? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could automate element behavior exactly when it appears or disappears, without messy manual code?

The Scenario

Imagine you want to add special effects to HTML elements when they appear, change, or disappear on your page. You try to do this by manually finding elements and adding event listeners or styles every time something changes.

The Problem

Manually tracking elements is tiring and error-prone. You might forget to clean up listeners, causing bugs or slowdowns. Also, updating effects when data changes means writing repetitive code that's hard to maintain.

The Solution

Vue's directive hooks like mounted, updated, and unmounted let you attach code that runs exactly when an element appears, updates, or is removed. This keeps your code clean, automatic, and reliable.

Before vs After
Before
const el = document.querySelector('#myEl');
el.style.color = 'red';
el.addEventListener('click', () => alert('Clicked!'));
After
const myDirective = {
  mounted(el) { el.style.color = 'red'; el.onclick = () => alert('Clicked!'); },
  unmounted(el) { el.onclick = null; }
};
What It Enables

You can easily add, update, and clean up element behaviors tied to their lifecycle without messy manual code.

Real Life Example

Think of a tooltip that appears when you hover over a button and disappears when you move away. Directive hooks let you add and remove the tooltip cleanly as the button enters or leaves the page.

Key Takeaways

Manual element handling is slow and error-prone.

Directive hooks run code automatically at key element lifecycle moments.

This makes your UI code cleaner, safer, and easier to maintain.