JAVASCRIPT

Creating Custom Global and Local Directives

Enhance DOM elements with reusable low-level behavior using Vue 3 custom directives, illustrating both global registration and local component-scoped usage.

// main.js (for global directive)
import { createApp } from 'vue';
import App from './App.vue';

const app = createApp(App);

// Register a global custom directive called `v-focus`
app.directive('focus', {
  // When the bound element is mounted into the DOM...
  mounted(el) {
    // Focus the element
    el.focus();
  }
});

app.mount('#app');

// MyComponent.vue (for local directive and usage)
<template>
  <div>
    <label>Global Focus Input: <input v-focus /></label>
    <br/>
    <label>Custom Text Color: <span v-color:text="'blue'">This text is blue.</span></label>
    <br/>
    <label>Custom Background Color: <span v-color:background="'yellow'">This background is yellow.</span></label>
  </div>
</template>

<script setup>
import { ref } from 'vue';

// Register a local custom directive called `v-color`
const vColor = {
  mounted(el, binding) {
    const type = binding.arg === 'text' ? 'color' : 'backgroundColor';
    el.style[type] = binding.value;
  },
  updated(el, binding) {
    const type = binding.arg === 'text' ? 'color' : 'backgroundColor';
    el.style[type] = binding.value;
  }
};
</script>
How it works: This snippet demonstrates how to create and use custom directives in Vue 3. The `v-focus` directive is globally registered in `main.js`, allowing it to be used on any element in the application to automatically focus it upon mounting. The `v-color` directive is locally registered within `MyComponent.vue` using a setup script. It accepts arguments (`text` or `background`) and a value (a color string) to dynamically set the element's text or background color. Directives provide a powerful way to encapsulate reusable low-level DOM manipulation logic.

Need help integrating this into your project?

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

Hire DigitalCodeLabs