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.