What if you could add powerful behaviors to elements with just a simple tag?
Creating custom directives in Vue - Why You Should Know This
Imagine you want to add the same special behavior, like focusing an input or changing colors on hover, to many elements in your app by writing plain JavaScript for each one.
Manually adding event listeners and DOM changes everywhere is repetitive, easy to forget, and makes your code messy and hard to maintain.
Custom directives let you package that behavior once and reuse it simply by adding a special attribute to any element, keeping your code clean and consistent.
const input = document.querySelector('#myInput'); input.addEventListener('focus', () => { input.style.backgroundColor = 'yellow'; });
app.directive('highlight', { mounted(el) { el.addEventListener('focus', () => { el.style.backgroundColor = 'yellow'; }); } }); // In template: <input v-highlight>
You can create reusable, easy-to-apply behaviors that keep your templates simple and your JavaScript organized.
Adding a custom directive to automatically focus form fields when a modal opens, without repeating code for every input.
Manual DOM handling is repetitive and error-prone.
Custom directives package behavior for easy reuse.
They keep your code clean and your app consistent.