JAVASCRIPT

Custom Global Directives in Vue 3

Extend Vue's functionality with custom global directives. This snippet shows how to create and register a directive for common DOM interactions like auto-focusing elements.

// src/directives/VFocus.js
const vFocus = {
  mounted: (el) => {
    el.focus();
  },
  // You can also define updated, beforeMount, beforeUpdate, beforeUnmount, unmounted
};

export default vFocus;

// src/main.js (global registration)
import { createApp } from 'vue';
import App from './App.vue';
import vFocus from './directives/VFocus';

const app = createApp(App);

app.directive('focus', vFocus); // Register the directive globally

app.mount('#app');

// src/components/AutoFocusInput.vue (example usage)
<template>
  <div>
    <p>This input will automatically focus:</p>
    <input v-focus type="text" placeholder="I'm focused!" />
    <br />
    <p>This input will not:</p>
    <input type="text" placeholder="Not focused" />
  </div>
</template>
How it works: Custom directives in Vue 3 allow you to encapsulate reusable low-level DOM manipulation logic. This example demonstrates creating a simple `v-focus` directive that automatically focuses an element when it's mounted. Directives are registered globally using `app.directive()` and can implement various lifecycle hooks like `mounted`, `updated`, and `unmounted` to interact with the DOM at different stages of an element's lifecycle. They provide a powerful way to add custom behavior to your HTML elements.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs