JAVASCRIPT
Create a Custom Global Directive in Vue 3
Understand how to define and register a custom global directive in Vue 3 to add reusable, low-level DOM manipulation directly to your HTML elements.
// directives/vFocus.js
export const vFocus = {
mounted: (el) => {
el.focus();
},
// You can also define other hooks: created, beforeMount, beforeUpdate, updated, beforeUnmount, unmounted
// For example, to handle dynamic focus:
// updated: (el, binding) => {
// if (binding.value) {
// el.focus();
// }
// }
};
// main.js (or wherever your app is mounted)
import { createApp } from 'vue';
import App from './App.vue';
import { vFocus } from './directives/vFocus';
const app = createApp(App);
// Register the custom directive globally
app.directive('focus', vFocus);
app.mount('#app');
// Usage in a Vue component (e.g., App.vue)
// <template>
// <div>
// <h2>Custom Directive Example</h2>
// <input v-focus type="text" placeholder="I will be focused on load" />
// <input type="text" placeholder="I will not be focused" />
// </div>
// </template>
// <script setup>
// // No explicit import needed if the directive is registered globally
// </script>
How it works: This snippet demonstrates how to create and register a custom global directive in Vue 3. A directive is essentially a reusable piece of low-level DOM manipulation logic. The `vFocus` directive, defined in `directives/vFocus.js`, has a `mounted` hook that automatically calls the `focus()` method on the element it's applied to, once that element is inserted into the DOM. By registering it globally with `app.directive('focus', vFocus)` in `main.js`, any component in the application can use `v-focus` on an HTML element (e.g., `<input v-focus />`) to apply this behavior without needing local imports, making it a powerful way to encapsulate and reuse direct DOM interactions.