JAVASCRIPT

Custom Directive for Auto-Focusing an Input in Vue 3

Implement a Vue 3 custom directive to automatically focus an input field or any focusable DOM element when it's rendered. Enhance user experience with declarative focus management.

// directives/vFocus.js
export const vFocus = {
  mounted: (el) => {
    el.focus();
  }
};

// main.js (or wherever you register global directives)
import { createApp } from 'vue';
import App from './App.vue';
import { vFocus } from './directives/vFocus';

const app = createApp(App);
app.directive('focus', vFocus); // Register globally
app.mount('#app');

// Component.vue (example usage)
<template>
  <div>
    <label for="nameInput">Name:</label>
    <input type="text" id="nameInput" v-focus />
    <label for="emailInput">Email:</label>
    <input type="email" id="emailInput" />
    <button>Submit</button>
  </div>
</template>

<script setup>
// No script needed for basic usage if globally registered
// If not globally registered, you'd import and register locally:
// import { vFocus } from '../directives/vFocus';
// const vFocusLocal = vFocus; // for template usage via <script setup>
</script>
How it works: This snippet demonstrates creating a custom Vue 3 directive named `v-focus`. When applied to a DOM element, the `mounted` lifecycle hook within the directive's definition is triggered after the element is inserted into the DOM. Inside this hook, `el.focus()` is called, causing the specified input or focusable element to automatically gain focus. This provides a declarative and reusable way to manage focus behavior within Vue applications.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs