Copied to Clipboard
In this example, the v-focus directive focuses the input element whenever it is mounted to the DOM.
For local registration, you define the directive within the directives option of a component:
export default {
directives: {
focus: {
mounted(el) {
el.focus();
}
}
},
template: `<input v-focus />`
};
Custom directives shine in scenarios that require direct DOM manipulation, especially when such logic doesn’t belong in components or composables. Let's take a look at the following example of a directive to add a snowflake effect on hover:
app.directive('hover-snow', {
mounted(el) {
el.addEventListener('mouseenter', () => {
el.style.backgroundImage = 'url(https://example.com/snowflake.png)';
el.style.backgroundRepeat = 'no-repeat';
el.style.backgroundPosition = 'center';
});
el.addEventListener('mouseleave', () => {
el.style.backgroundImage = '';
});
},
unmounted(el) {
el.removeEventListener('mouseenter');
el.removeEventListener('mouseleave');
}
});
This directive sprinkles your elements with snowflakes, adding a touch of Christmas magic to your app.
Custom directives are ideal when:
-
Direct DOM Manipulation is Needed: For operations like focusing elements or integrating third-party libraries.
-
Reusability is Required: Encapsulate common DOM logic into a directive for consistency across components.
-
Avoiding Component Overhead: Use directives instead of components for simple DOM-related behavior, reducing boilerplate.
However, for more complex or state-driven logic, consider using composables or Vue components instead, as they integrate more naturally into Vue’s reactive system.
📖 Learn more
If you would like to learn more about Vue, Nuxt, JavaScript or other useful technologies, checkout VueSchool by clicking this link or by clicking the image below:
Vue School Link
It covers most important concepts while building modern Vue or Nuxt applications that can help you in your daily work or side projects 😉
✅ Summary
Well done! Vue 3’s custom directives provide a concise way to encapsulate and reuse DOM manipulation logic. They complement Vue’s declarative programming paradigm, enabling developers to handle edge cases and extend functionality effortlessly. By understanding how and when to use them, you can enhance your applications with clean and maintainable code.
Take care and see you next time! And Merry Christmas! 🎄
And happy coding as always 🖥️