JAVASCRIPT
Creating a Custom Directive for Auto-Focusing Elements
Implement a reusable Vue 3 custom directive to automatically focus input fields or other elements when they are rendered, enhancing user experience and accessibility.
// directives/vFocus.js
export const vFocus = {
// When the bound element is inserted into the DOM...
mounted(el) {
el.focus();
}
};
// main.js
import { createApp } from 'vue';
import App from './App.vue';
import { vFocus } from './directives/vFocus';
const app = createApp(App);
// Register the global directive
app.directive('focus', vFocus);
app.mount('#app');
// --- In a component (e.g., App.vue or another component) ---
<template>
<div>
<h1>Custom Focus Directive</h1>
<label>
Name:
<input type="text" v-focus />
</label>
<br><br>
<label>
Email:
<input type="email" />
</label>
<br><br>
<button @click="resetForm">Reset</button>
</div>
</template>
<script setup>
// If you want to use it locally in a component:
// import { defineDirective } from 'vue'; // (Not a real API, directives are imported and used directly)
// import { vFocus } from './directives/vFocus';
// const myLocalFocusDirective = vFocus; // Can be used as v-my-local-focus in template
const resetForm = () => {
console.log('Form reset logic here');
// In a real app, you might clear inputs here
};
</script>
How it works: Vue 3 custom directives allow you to abstract low-level DOM manipulation into reusable pieces of code. This snippet demonstrates creating a `v-focus` directive that automatically focuses an HTML element (e.g., an input field) as soon as it's inserted into the DOM. The `mounted` hook of the directive is called when the element is added to the document, and `el.focus()` is then executed. This is highly useful for improving user experience in forms or dynamic interfaces by guiding the user's attention.