JAVASCRIPT

Create a Custom Global Focus Directive in Vue 3

Implement a reusable custom directive in Vue 3 to automatically focus an input element when mounted, enhancing user experience and accessibility.

// main.js
import { createApp } from 'vue';
import App from './App.vue';

const app = createApp(App);

app.directive('focus', {
  // called when the bound element's parent component and all its children
  // are mounted.
  mounted(el) {
    el.focus();
  }
});

app.mount('#app');

// In a Vue component:
// <template>
//   <div>
//     <label for="name">Name:</label>
//     <input type="text" id="name" v-focus>
//     <label for="email">Email:</label>
//     <input type="email" id="email">
//   </div>
// </template>
//
// <script setup>
// // No specific script needed here as the directive is global
// </script>
How it works: This code snippet demonstrates how to register a custom global directive named `v-focus` in a Vue 3 application. The `mounted` hook of the directive is triggered when the element it's bound to is inserted into the DOM. Inside this hook, `el.focus()` is called, causing the input field (or any element the directive is applied to) to automatically receive focus, which is useful for form initializations or accessibility improvements.

Need help integrating this into your project?

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

Hire DigitalCodeLabs