JAVASCRIPT
Implementing Custom Directives in Vue 3
Extend Vue 3's capabilities by creating custom directives for low-level DOM manipulation, adding reusable and declarative behavior directly to your HTML elements.
// main.js (or where your Vue app is created)
import { createApp } from 'vue';
import App from './App.vue';
const app = createApp(App);
// Define a custom directive for auto-focus
app.directive('focus', {
// When the bound element is mounted into the DOM...
mounted(el) {
el.focus();
},
});
// Define a custom directive for changing background color on hover
app.directive('hover-color', {
mounted(el, binding) {
const defaultColor = binding.arg || 'lightblue'; // Use argument if present, else default
const hoverColor = binding.value || 'lightcoral'; // Use value if present, else default
let originalColor = el.style.backgroundColor;
el.addEventListener('mouseenter', () => {
originalColor = el.style.backgroundColor;
el.style.backgroundColor = hoverColor;
});
el.addEventListener('mouseleave', () => {
el.style.backgroundColor = originalColor;
});
},
// Clean up event listeners when the element is unmounted
beforeUnmount(el) {
// It's good practice to remove listeners, though for simple cases Vue might handle it.
// For 'hover-color', if element is removed, listeners are garbage collected with it.
// For more complex cases, explicitly remove them.
}
});
app.mount('#app');
// App.vue (or any component)
<template>
<div>
<input v-focus placeholder="This input will auto-focus">
<p v-hover-color:green="'yellow'">Hover over me to change my background!</p>
<button v-hover-color>Hover for default color change</button>
</div>
</template>
<script setup>
// No script needed here for the directives themselves, as they are global.
</script>
How it works: This example demonstrates creating and registering custom directives in Vue 3. Directives allow you to encapsulate reusable DOM manipulation logic. The `v-focus` directive automatically focuses an input element when it's mounted. The `v-hover-color` directive changes an element's background color on hover, supporting dynamic colors via arguments and values. Custom directives provide a powerful way to add declarative behavior to elements, extending Vue's functionality for specific, low-level DOM interactions in a clean and modular fashion.