JAVASCRIPT

Implement a Custom Autofocus Directive in Vue 3

Create a reusable Vue 3 custom directive (v-autofocus) to automatically focus on an input or element when its component is mounted, enhancing user experience for forms.

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

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

const app = createApp(App);
app.directive('autofocus', vAutofocus);
app.mount('#app');

// MyComponent.vue
<template>
  <div>
    <label for="username">Username:</label>
    <input type="text" id="username" v-autofocus />
    <label for="email">Email:</label>
    <input type="email" id="email" />
  </div>
</template>

<script setup>
// No script logic needed for v-autofocus in component
</script>
How it works: This snippet demonstrates how to create and use a custom directive `v-autofocus` in Vue 3. The `vAutofocus` object defines a `mounted` hook which is called when the element the directive is bound to is inserted into the DOM. Inside this hook, `el.focus()` is called, causing the element to automatically receive focus. The directive is then globally registered in `main.js` and can be used on any HTML element in templates, providing an immediate focus on an element upon component rendering.

Need help integrating this into your project?

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

Hire DigitalCodeLabs