JAVASCRIPT
Creating a Custom Vue 3 `v-focus` Directive
Enhance user experience in Vue 3 by developing a custom `v-focus` directive to automatically focus input fields when a component mounts, improving accessibility.
// src/main.js or src/directives/focus.js
export const focusDirective = {
mounted: (el) => {
el.focus();
},
updated: (el) => {
// Optional: if you want to refocus on update
// el.focus();
}
};
// src/main.js (if defined in main.js)
import { createApp } from 'vue';
import App from './App.vue';
import { focusDirective } from './directives/focus'; // If in a separate file
const app = createApp(App);
app.directive('focus', focusDirective);
app.mount('#app');
// src/components/FocusInput.vue
<template>
<div>
<label>Auto-focused Input:</label>
<input v-focus type="text" placeholder="This input is focused on load" />
<br/>
<label>Another Input:</label>
<input type="text" placeholder="Normal input" />
</div>
</template>
How it works: This snippet illustrates how to create and register a custom Vue 3 directive named `v-focus`. The `focusDirective` object defines lifecycle hooks, specifically `mounted`, which is called when the element is inserted into the DOM. Inside this hook, `el.focus()` is called to programmatically set focus on the input field. The directive is registered globally in `main.js` using `app.directive()`, allowing it to be used declaratively as `v-focus` on any element in the application.