0
0
Vueframework~15 mins

Directive hooks (mounted, updated, unmounted) in Vue - Deep Dive

Choose your learning style9 modes available
Overview - Directive hooks (mounted, updated, unmounted)
What is it?
Directive hooks in Vue are special functions that run at specific times during a directive's life. They let you control what happens when a directive is added to an element, when the element updates, or when it is removed. These hooks are named mounted, updated, and unmounted. They help you add custom behavior to elements in your Vue app.
Why it matters
Without directive hooks, you would have limited control over how custom directives behave during their lifecycle. This would make it hard to manage things like event listeners or animations tied to elements. Directive hooks solve this by giving you clear moments to run code, making your app more interactive and efficient. Without them, your app might leak memory or behave unpredictably.
Where it fits
Before learning directive hooks, you should understand Vue directives and the basics of Vue components. After mastering directive hooks, you can explore advanced Vue features like custom directives with arguments and modifiers, and Vue's Composition API for more flexible logic.
Mental Model
Core Idea
Directive hooks are like checkpoints where Vue lets you run code when a directive starts, changes, or ends on an element.
Think of it like...
Imagine a stage play where actors enter, perform, and exit. Mounted is when the actor steps on stage, updated is when the actor changes their act, and unmounted is when the actor leaves the stage.
┌─────────────┐
│ Directive   │
│ Lifecycle   │
└─────┬───────┘
      │
      ▼
┌─────────────┐   ┌─────────────┐   ┌─────────────┐
│ Mounted     │ → │ Updated     │ → │ Unmounted   │
│ (enter)     │   │ (change)    │   │ (exit)      │
└─────────────┘   └─────────────┘   └─────────────┘
Build-Up - 7 Steps
1
FoundationWhat are Vue directives?
🤔
Concept: Introduce Vue directives as special markers on HTML elements that add behavior.
In Vue, directives are special attributes like v-if or v-model that tell Vue to do something with the element. For example, v-if shows or hides an element based on a condition. Custom directives let you create your own behaviors.
Result
You understand that directives control element behavior in Vue templates.
Knowing what directives do is essential before learning how to control their lifecycle with hooks.
2
FoundationIntroduction to directive lifecycle hooks
🤔
Concept: Explain that directives have lifecycle hooks to run code at key moments.
Vue calls special functions during a directive's life: mounted when the directive is first applied, updated when the element changes, and unmounted when the directive is removed. These let you add or clean up behavior.
Result
You see that directive hooks let you run code exactly when needed.
Understanding these hooks helps you manage side effects and keep your app clean.
3
IntermediateUsing the mounted hook effectively
🤔Before reading on: do you think mounted runs once or multiple times during a directive's life? Commit to your answer.
Concept: Learn that mounted runs once when the directive is attached to the element.
The mounted hook runs once when the directive is first bound to the element. Use it to set up things like event listeners or initial styles. For example: const myDirective = { mounted(el) { el.style.color = 'blue' } } This changes the text color when the directive starts.
Result
The element's text color changes to blue when the directive is applied.
Knowing mounted runs once prevents repeated setup and potential bugs.
4
IntermediateUnderstanding the updated hook
🤔Before reading on: does updated run only when directive value changes or on every component update? Commit to your answer.
Concept: The updated hook runs whenever the element or directive's value changes after mounting.
Updated runs after the element or directive's value changes. Use it to react to changes, like updating styles or attributes. Example: const myDirective = { updated(el, binding) { el.style.color = binding.value } } If the value changes from 'blue' to 'red', updated runs and changes the color.
Result
The element's color updates dynamically when the directive's value changes.
Understanding updated lets you respond to changes without remounting.
5
IntermediateCleaning up with the unmounted hook
🤔Before reading on: do you think unmounted runs before or after the element is removed? Commit to your answer.
Concept: Unmounted runs when the directive is removed, letting you clean up resources.
Use unmounted to remove event listeners or timers to avoid memory leaks. Example: const myDirective = { mounted(el) { el._clickHandler = () => alert('Clicked!') el.addEventListener('click', el._clickHandler) }, unmounted(el) { el.removeEventListener('click', el._clickHandler) } } This ensures no leftover listeners after removal.
Result
Event listeners are properly removed when the directive is gone.
Cleaning up prevents bugs and keeps your app efficient.
6
AdvancedHandling directive arguments and modifiers
🤔Before reading on: can directive hooks access arguments and modifiers? Commit to your answer.
Concept: Directive hooks receive info about arguments and modifiers to customize behavior.
Hooks get a binding object with value, argument, and modifiers. For example: const myDirective = { mounted(el, binding) { if (binding.modifiers.bold) { el.style.fontWeight = 'bold' } if (binding.arg === 'color') { el.style.color = binding.value } } } This lets you write flexible directives.
Result
Directives can change behavior based on arguments and modifiers.
Using binding details makes directives reusable and powerful.
7
ExpertAvoiding common pitfalls with directive hooks
🤔Before reading on: do you think updated always runs after mounted or can it run multiple times independently? Commit to your answer.
Concept: Understand subtle lifecycle timing and how to avoid memory leaks or redundant updates.
Updated can run many times after mounted, so avoid heavy work there. Also, always clean up in unmounted to prevent leaks. For example, if you add event listeners in updated without removing old ones, you get duplicates. Use mounted for setup, updated for light changes, and unmounted for cleanup.
Result
Your directives run efficiently without bugs or leaks.
Knowing lifecycle timing prevents performance issues and hard-to-find bugs.
Under the Hood
Vue tracks directives on elements and calls hooks at specific DOM lifecycle events. When a directive is first bound, Vue calls mounted. On reactive data changes affecting the directive, Vue calls updated. When the element or directive is removed, Vue calls unmounted. Vue manages these calls efficiently to sync DOM and data.
Why designed this way?
This design separates concerns: setup, update, and cleanup. It matches the natural lifecycle of DOM elements and reactive data. Alternatives like running code only on updates would cause inefficiency or leaks. This clear lifecycle model helps developers write predictable, maintainable code.
┌───────────────┐
│ Vue Template  │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Directive     │
│ Instance      │
└──────┬────────┘
       │
       ▼
┌───────────────┐       ┌───────────────┐       ┌───────────────┐
│ mounted hook  │──────▶│ updated hook  │──────▶│ unmounted hook│
└───────────────┘       └───────────────┘       └───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does the mounted hook run every time the component updates? Commit to yes or no.
Common Belief:Mounted runs every time the component or element updates.
Tap to reveal reality
Reality:Mounted runs only once when the directive is first attached to the element.
Why it matters:Misusing mounted for updates causes redundant setup and performance issues.
Quick: Does updated run only when the directive's value changes? Commit to yes or no.
Common Belief:Updated runs only when the directive's value changes.
Tap to reveal reality
Reality:Updated runs after every component update that affects the element, even if the directive's value is unchanged.
Why it matters:Assuming updated runs only on value change can lead to unexpected repeated executions.
Quick: Is it safe to add event listeners in updated without removing old ones? Commit to yes or no.
Common Belief:You can add event listeners in updated without cleanup; Vue handles it.
Tap to reveal reality
Reality:You must manually remove event listeners in unmounted to avoid memory leaks and duplicate handlers.
Why it matters:Ignoring cleanup causes bugs and performance degradation over time.
Quick: Does unmounted run before or after the element is removed from the DOM? Commit to before or after.
Common Belief:Unmounted runs after the element is removed from the DOM.
Tap to reveal reality
Reality:Unmounted runs just before the element is removed, allowing cleanup while the element still exists.
Why it matters:Misunderstanding this timing can cause cleanup code to fail if it expects the element to be gone.
Expert Zone
1
Updated hook can run multiple times even if directive value is unchanged due to parent component updates, so optimize for idempotency.
2
Using unmounted to clean up resources is critical in Single Page Applications to prevent memory leaks during navigation.
3
Directive hooks receive a vnode and prevVNode parameter (in Vue 3) allowing fine-grained control and comparison for advanced use cases.
When NOT to use
Avoid using directive hooks for complex state management or logic better handled by components or the Composition API. Use hooks only for direct DOM manipulations or side effects tied to elements.
Production Patterns
In production, directives often manage third-party libraries (e.g., tooltips), custom input masks, or animations. Hooks ensure proper setup and teardown, preventing leaks and ensuring smooth user experience.
Connections
React useEffect Hook
Both manage side effects tied to component lifecycle but React uses hooks inside components while Vue uses directive hooks for element-level control.
Understanding Vue directive hooks clarifies how frameworks handle side effects differently but with similar goals of setup and cleanup.
Event Listeners in Web Development
Directive hooks often add and remove event listeners, mirroring manual DOM event management.
Knowing how event listeners work in plain JavaScript helps grasp why cleanup in unmounted is crucial.
Theater Stage Management
Directive hooks correspond to actors entering, performing, and exiting the stage.
This analogy helps understand the timing and purpose of each hook in managing element behavior.
Common Pitfalls
#1Adding event listeners in updated without removing old ones.
Wrong approach:const myDirective = { updated(el) { el.addEventListener('click', () => alert('Clicked!')) } }
Correct approach:const myDirective = { mounted(el) { el._clickHandler = () => alert('Clicked!') el.addEventListener('click', el._clickHandler) }, unmounted(el) { el.removeEventListener('click', el._clickHandler) } }
Root cause:Misunderstanding that updated runs multiple times and that event listeners must be cleaned up manually.
#2Trying to access the element after unmounted runs.
Wrong approach:const myDirective = { unmounted(el) { console.log(el.parentNode.innerHTML) // assuming element is gone } }
Correct approach:const myDirective = { unmounted(el) { // Cleanup code here, element still exists console.log('Cleaning up before removal') } }
Root cause:Assuming unmounted runs after element removal instead of before.
#3Running heavy computations inside updated hook.
Wrong approach:const myDirective = { updated(el, binding) { for(let i=0; i<1000000; i++) { /* heavy work */ } el.textContent = binding.value } }
Correct approach:const myDirective = { mounted(el, binding) { // Heavy setup once }, updated(el, binding) { el.textContent = binding.value } }
Root cause:Not realizing updated can run many times, causing performance issues.
Key Takeaways
Directive hooks let you run code at key moments: when a directive starts, updates, and ends on an element.
Mounted runs once when the directive is attached, updated runs on every relevant change, and unmounted runs before removal for cleanup.
Proper use of these hooks prevents memory leaks, redundant work, and bugs in your Vue apps.
Directive hooks receive useful info like arguments and modifiers to customize behavior.
Understanding the lifecycle and timing of these hooks is essential for writing efficient and maintainable custom directives.