← Back to all snippets
JAVASCRIPT

Creating a Custom Vue 3 Directive for Auto-Focus

Explore how to create a custom Vue 3 directive to automatically focus an input element when a component is mounted, enhancing user experience.

// src/directives/VFocus.js
export default {
  // when the bound element is mounted into the DOM
  mounted(el) {
    el.focus();
  }
};

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

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

// src/App.vue
<template>
  <div>
    <h1>Custom Directive Example</h1>
    <input v-focus type="text" placeholder="I will be focused automatically" />
    <input type="text" placeholder="I will not" />
  </div>
</template>
How it works: This snippet illustrates how to create and register a custom Vue 3 directive. The `v-focus` directive, defined in `VFocus.js`, uses the `mounted` hook to automatically call `focus()` on the HTML element it's bound to, immediately after the element is inserted into the DOM. It's then registered globally in `main.js` and can be used declaratively in any component's template, providing reusable DOM manipulation logic.

Need help integrating this into your project?

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

Hire DigitalCodeLabs