JAVASCRIPT
Create a Custom Focus Directive in Vue 3
Extend Vue 3's capabilities by creating a custom directive (e.g., `v-focus`) to directly manipulate the DOM for specific behaviors like auto-focusing input fields.
// main.js (or an entry file)
import { createApp } from 'vue';
import App from './App.vue';
const app = createApp(App);
// Register a global custom directive called v-focus
app.directive('focus', {
// When the bound element is mounted into the DOM...
mounted(el) {
// Focus the element
el.focus();
},
// You can also define other hooks: updated, beforeMount, beforeUpdate, beforeUnmount, unmounted
// For example, to ensure focus reapplies if the component is re-rendered and element becomes focusable again
updated(el) {
// Optional: Re-focus if element is updated and still active.
// A simple focus directive might only need 'mounted'.
}
});
app.mount('#app');
// MyComponent.vue
<template>
<div>
<p>Click away from the input, then toggle the button to see it auto-focus again.</p>
<input v-model="message" v-focus placeholder="This input auto-focuses!" />
<p>Message: {{ message }}</p>
<button @click="toggleSecondInput = !toggleSecondInput">
Toggle Second Input (with focus on mount)
</button>
<input v-if="toggleSecondInput" v-focus placeholder="Second input focuses on mount!" />
</div>
</template>
<script setup>
import { ref } from 'vue';
const message = ref('');
const toggleSecondInput = ref(false);
</script>
How it works: This snippet demonstrates how to create and register a custom directive (`v-focus`) in Vue 3. Directives are powerful tools for applying low-level DOM manipulations or behaviors when components are mounted, updated, or unmounted. The `v-focus` directive, applied to an input element, automatically focuses it when the element is inserted into the DOM (via the `mounted` hook). This provides a reusable way to implement common UI interactions without cluttering component logic, making your templates more declarative and expressive.