JAVASCRIPT
Creating Custom Vue 3 Directives for Reusable DOM Logic
Extend Vue 3's functionality by creating custom directives. Learn to add reusable DOM manipulation logic, like auto-focusing elements, with ease.
// main.js or a plugin file
import { createApp } from 'vue';
import App from './App.vue';
const app = createApp(App);
app.directive('focus', {
mounted(el) {
el.focus();
}
});
app.mount('#app');
<!-- App.vue -->
<template>
<div>
<h1>Custom Directive Example</h1>
<p>Input below should automatically focus on page load:</p>
<input type="text" v-focus placeholder="I will focus automatically">
<br><br>
<input type="text" placeholder="Another input">
</div>
</template>
<script setup>
// No specific script logic needed for this example,
// the directive is registered globally.
</script>
How it works: Custom directives in Vue 3 allow you to encapsulate reusable DOM manipulation logic. This example defines a global `v-focus` directive that automatically focuses an input element when it's mounted to the DOM. Directives provide lifecycle hooks like `mounted`, `updated`, and `unmounted`, enabling precise control over an element's behavior based on its state within the component lifecycle. This is ideal for abstracting common DOM interactions beyond what standard props or events can offer.