JAVASCRIPT
Vue 3 Custom Directive for Automatic Input Focus
Create a custom Vue 3 directive to automatically focus an input element when a component mounts, improving user experience in forms or dynamic content.
// directives/v-focus.js
export const vFocus = {
// When the bound element is inserted into the DOM...
mounted(el) {
// Focus the element
el.focus();
},
// If the value changes, you could also re-focus or add other logic
// updated(el, binding) {
// if (binding.value) { // Only focus if directive value is true
// el.focus();
// }
// }
};
// main.js (or any entry file)
import { createApp } from 'vue';
import App from './App.vue';
import { vFocus } from './directives/v-focus';
const app = createApp(App);
// Register the custom directive globally
app.directive('focus', vFocus);
app.mount('#app');
// ComponentUsingFocus.vue
<template>
<div>
<h2>Custom Focus Directive Example</h2>
<p>This input will automatically get focus when the component mounts.</p>
<input type="text" v-focus placeholder="I will be focused!" />
<p>This input requires manual focus.</p>
<input type="text" placeholder="I won't be focused automatically." />
<p>You can conditionally apply it too:</p>
<input type="text" v-focus="isEditable" placeholder="Focused if editable" />
<button @click="isEditable = !isEditable">Toggle Focus Condition (currently {{ isEditable }})</button>
</div>
</template>
<script setup>
import { ref } from 'vue';
const isEditable = ref(true);
</script>
How it works: This snippet demonstrates creating a custom Vue 3 directive, `v-focus`. When applied to an HTML element (e.g., `<input v-focus />`), the `mounted` hook of the directive automatically calls `el.focus()`, giving focus to that element as soon as it's inserted into the DOM. This is highly useful for improving user experience in forms, modals, or dynamic content where a specific input needs immediate attention.