JAVASCRIPT
Create a Custom Vue 3 Directive for Auto-Focusing Inputs
Learn to create a reusable Vue 3 custom directive to automatically focus an input or element when it's rendered or updated, enhancing user experience in forms and modals.
// directives/v-focus.js
export const vFocus = {
mounted: (el) => el.focus(),
};
// main.js or relevant setup file
import { createApp } from 'vue';
import App from './App.vue';
import { vFocus } from './directives/v-focus';
const app = createApp(App);
app.directive('focus', vFocus);
app.mount('#app');
// Usage in a component
// <template>
// <div>
// <input v-focus type="text" placeholder="I will be focused on load" />
// <p>Other content...</p>
// </div>
// </template>
How it works: This snippet demonstrates how to create and register a custom Vue 3 directive named `v-focus`. The directive uses the `mounted` hook to automatically call the `focus()` method on the element it's applied to, ensuring that the element gains focus as soon as it's inserted into the DOM. This is particularly useful for improving accessibility and user flow in forms, search fields, or modal dialogs, where an element should receive immediate user input.