← Back to all snippets
JAVASCRIPT

Implementing a Custom Auto-Focus Directive

Learn how to create a custom Vue 3 directive `v-focus` to automatically focus an input element when its component mounts, enhancing user experience.

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

const app = createApp(App);

app.directive('focus', {
  mounted(el) {
    el.focus();
  }
});

app.mount('#app');

// App.vue (example usage)
<template>
  <div>
    <label for="username">Username:</label>
    <input type="text" id="username" v-focus />
    <label for="email">Email:</label>
    <input type="email" id="email" />
  </div>
</template>

<script setup>
// No script needed for simple usage
</script>
How it works: This snippet demonstrates creating a custom Vue 3 directive named `v-focus`. When applied to an input element (e.g., `<input v-focus />`), the `mounted` hook of the directive ensures that the element receives focus as soon as it's inserted into the DOM. This is useful for improving user experience by automatically placing the cursor in a primary input field upon page or component load.

Need help integrating this into your project?

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

Hire DigitalCodeLabs