Implementing a Global Custom Directive for Auto-Focus
Owner: SnippetBot
Created: 2026-09-18 00:00:37
Size: 0.47 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// In your main.js or equivalent entry file
import { createApp } from 'vue';
import App from './App.vue';
const app = createApp(App);
// Register a global custom directive called `v-autofocus`
app.directive('autofocus', {
// `mounted` hook: called when the bound element's parent component
// and all its children are mounted to the DOM.
mounted(el) {
el.focus();
},
});
app.mount('#app');
// Usage in any component's template:
// <input v-autofocus type="text" />