JAVASCRIPT
Building a Custom Directive for Element Focus
Create a custom Vue 3 directive to automatically focus input elements on mount, demonstrating how to encapsulate reusable DOM behavior efficiently.
// directives/vFocus.js
export const vFocus = {
// Called when the bound element's parent component and all its children are mounted.
mounted(el) {
el.focus();
},
};
// main.js (or wherever your app is initialized)
// import { createApp } from 'vue';
// import App from './App.vue';
// import { vFocus } from './directives/vFocus';
// const app = createApp(App);
// app.directive('focus', vFocus);
// app.mount('#app');
// Usage in a Vue component (e.g., App.vue):
// <template>
// <div>
// <h1>Custom Focus Directive</h1>
// <input type="text" placeholder="This input will be focused" v-focus />
// <input type="text" placeholder="This input will not be focused" />
// </div>
// </template>
// <script setup>
// // No explicit import needed in script setup if globally registered
// </script>
How it works: This snippet demonstrates how to create and use a custom directive in Vue 3 to automatically focus an input element when its component is mounted. The `vFocus` directive is defined with a `mounted` hook that directly calls the `focus()` method on the bound DOM element. Custom directives are a powerful feature for encapsulating reusable, low-level DOM manipulations, making your templates cleaner and more declarative for specific element behaviors.