Directive hooks let you run code at specific times when a custom directive is added, changed, or removed from an element. This helps you control element behavior easily.
Directive hooks (mounted, updated, unmounted) in Vue
const myDirective = { mounted(el, binding, vnode, prevVnode) { // runs when directive is first attached to element }, updated(el, binding, vnode, prevVnode) { // runs when element or binding updates }, unmounted(el, binding, vnode, prevVnode) { // runs when directive is removed from element } };
mounted runs once when the directive is first added.
updated runs whenever the bound value or element updates.
const focusDirective = {
mounted(el) {
el.focus();
}
};const colorDirective = {
mounted(el, binding) {
el.style.color = binding.value;
},
updated(el, binding) {
el.style.color = binding.value;
}
};const cleanupDirective = { mounted(el) { const handler = () => alert('Clicked!'); el._clickHandler = handler; el.addEventListener('click', handler); }, unmounted(el) { if (el._clickHandler) { el.removeEventListener('click', el._clickHandler); delete el._clickHandler; } } };
This Vue component uses two custom directives. v-focus sets focus on the input when it appears. v-color changes the paragraph text color based on the textColor value. Clicking the button toggles the color between blue and green.
<template> <input v-focus /> <p v-color="textColor">This text changes color.</p> <button @click="changeColor">Change Color</button> </template> <script> export default { data() { return { textColor: 'blue' }; }, methods: { changeColor() { this.textColor = this.textColor === 'blue' ? 'green' : 'blue'; } }, directives: { focus: { mounted(el) { el.focus(); } }, color: { mounted(el, binding) { el.style.color = binding.value; }, updated(el, binding) { el.style.color = binding.value; } } } }; </script>
Always clean up event listeners or timers in unmounted to avoid memory leaks.
Use binding.value to access the current value passed to the directive.
Directive hooks receive the element and useful info to control behavior precisely.
Directive hooks let you run code when a directive is added, updated, or removed.
mounted runs once when the directive attaches.
updated runs on data or element changes.
unmounted runs when the directive is removed, perfect for cleanup.
Practice
mounted hook in a Vue directive do?Solution
Step 1: Understand the purpose of
Themountedhookmountedhook runs once when the directive is first attached to the element in the DOM.Step 2: Compare with other hooks
Theupdatedhook runs on data or element changes, andunmountedruns when the directive is removed, so they do not match the description ofmounted.Final Answer:
Runs once when the directive is attached to the element -> Option BQuick Check:
mounted = runs once on attach [OK]
- Confusing mounted with updated hook
- Thinking mounted runs multiple times
- Mixing unmounted with mounted
unmounted hook in a Vue directive?Solution
Step 1: Recall the correct hook name
The correct hook name for cleanup when a directive is removed isunmounted.Step 2: Check syntax correctness
The hook is defined as a function with parameterselandbinding, sounmounted(el, binding) { /* code */ }is correct.Final Answer:
unmounted(el, binding) { /* code */ } -> Option DQuick Check:
Correct hook name is unmounted [OK]
- Using 'unmount' instead of 'unmounted'
- Confusing with lifecycle hooks like 'destroyed'
- Adding 'on' prefix incorrectly
const myDirective = {
mounted(el) {
console.log('Mounted')
},
updated(el) {
console.log('Updated')
},
unmounted(el) {
console.log('Unmounted')
}
}Solution
Step 1: Understand when each hook runs
mountedruns once when directive attaches,updatedruns on element or data changes,unmountedruns when directive is removed.Step 2: Analyze the scenario
When the element's text changes, theupdatedhook runs, so bothMounted(once) andUpdated(on change) will log.Final Answer:
'Mounted' then 'Updated' will log on text change -> Option AQuick Check:
mounted once, updated on change [OK]
- Thinking updated runs only once
- Expecting unmounted to run on text change
- Ignoring mounted logs
const directive = {
mounted(el) {
console.log('Mounted')
},
updated() {
console.log('Updated')
},
unmounted(el) {
console.log('Unmounted')
}
}Solution
Step 1: Check parameters for each hook
Directive hooks receive the element as the first parameter. Theupdatedhook is missing theelparameter.Step 2: Verify other hooks
mountedandunmountedcorrectly haveelparameter. Theunmountedhook is correctly named.Final Answer:
The updated hook is missing the 'el' parameter -> Option CQuick Check:
All hooks need 'el' parameter [OK]
- Omitting parameters in hooks
- Confusing lifecycle hook names
- Assuming no parameters needed
Solution
Step 1: Determine when to add event listener
The listener should be added once when the directive attaches, so usemounted.Step 2: Determine when to remove event listener
Cleanup should happen when the directive is removed, so useunmountedto remove the listener.Final Answer:
Add listener in mounted, remove in unmounted -> Option AQuick Check:
mounted = add, unmounted = cleanup [OK]
- Adding/removing listeners in updated hook
- Removing listener before adding it
- Using unmounted to add listener
Ready to prove it?
Pass the test and this pattern moves unknown
