JAVASCRIPT
Create a Custom Vue 3 Directive for Auto-Focus
Discover how to build a reusable custom directive in Vue 3 to automatically focus an input element when it becomes visible or is rendered.
// directives/v-autofocus.js
export const vAutofocus = {
// Called when the bound element's parent component and all its children are mounted.
mounted: (el) => {
el.focus();
},
// You can also define other hooks like updated, beforeUpdate, etc.
// updated: (el) => {
// console.log('Element updated!', el);
// }
};
// main.js
import { createApp } from 'vue';
import App from './App.vue';
import { vAutofocus } from './directives/v-autofocus';
const app = createApp(App);
app.directive('autofocus', vAutofocus); // Register the directive globally
app.mount('#app');
// Component.vue
<template>
<div>
<label for="name">Your Name:</label>
<input type="text" id="name" v-autofocus placeholder="This input auto-focuses!" />
<p>This input will automatically focus when the component mounts due to the custom directive.</p>
<input type="text" placeholder="Another input" />
</div>
</template>
<script setup>
// No script specific code needed if registered globally
</script>
How it works: Custom directives in Vue 3 provide a way to apply low-level DOM manipulations directly to elements, encapsulating reusable behavior. This example creates a `v-autofocus` directive that, when applied to an input element, automatically focuses it when the component is mounted. Directives are registered globally in `main.js` and can then be used anywhere in the application with `v-directive-name`.