JAVASCRIPT
Implementing a Custom Global v-focus Directive in Vue 3
Discover how to register and use a custom global directive in Vue 3, such as `v-focus`, to programmatically interact with DOM elements directly from your templates.
// main.js (or your app 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', {
// Called when the bound element is inserted into the DOM...
mounted(el) {
// Focus the element
el.focus();
}
});
app.mount('#app');
// MyComponent.vue
<template>
<div>
<h1>Custom Directive Example</h1>
<p>The input below will automatically focus on page load.</p>
<input type="text" v-focus placeholder="I'm focused!">
<input type="text" placeholder="Not focused">
</div>
</template>
<script setup>
// No specific script logic needed for v-focus in this component
</script>
How it works: Custom directives in Vue 3 provide a way to apply low-level DOM manipulations or side effects when specific events occur in the element's lifecycle. Here, we register a global `v-focus` directive in `main.js`. Its `mounted` hook is automatically called when the element it's bound to is inserted into the DOM. Inside `mounted`, `el.focus()` is called to set focus on the input element, making it active when the component loads.