JAVASCRIPT
Vue 3 Custom Directive for Auto-Focusing an Input
Create a custom Vue 3 directive (`v-focus`) to automatically focus an input element when it is mounted to the DOM, improving user experience for forms and interactive elements.
// src/directives/focus.js
export default {
// Called when the bound element's parent component and all its children have been mounted.
mounted(el) {
el.focus();
}
};
// src/main.js (or wherever you register global directives)
import { createApp } from 'vue';
import App from './App.vue';
import focusDirective from './directives/focus';
const app = createApp(App);
app.directive('focus', focusDirective);
app.mount('#app');
// src/App.vue
<script setup>
// No script needed here if directive is globally registered
// If locally registered:
// import focusDirective from './directives/focus';
// const vFocus = focusDirective;
</script>
<template>
<div class="p-8 bg-gray-100 min-h-screen">
<h1 class="text-3xl font-bold mb-6">Custom Focus Directive</h1>
<div class="bg-white p-6 rounded-lg shadow-md">
<p class="mb-4">The input below will automatically gain focus when the page loads:</p>
<input
v-focus
type="text"
placeholder="I'm auto-focused!"
class="p-3 border border-blue-300 rounded-md w-full focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
/>
<p class="mt-6 mb-4">This input requires manual focus:</p>
<input
type="text"
placeholder="I need a click to focus."
class="p-3 border border-gray-300 rounded-md w-full"
/>
</div>
</div>
</template>
How it works: This snippet demonstrates how to create and use a custom directive in Vue 3 to automatically focus an input element. The `v-focus` directive is defined with a `mounted` hook, which is executed once the element is inserted into the DOM. Inside this hook, `el.focus()` programmatically focuses the element. Directives are registered globally in `main.js` and then can be used declaratively on any element in your templates, providing a clean way to encapsulate direct DOM manipulations.