JAVASCRIPT

Create Custom Directives in Vue 3

Explore how to define and use custom directives in Vue 3 to encapsulate reusable DOM manipulation logic, allowing for direct interaction with elements' attributes and styles in a declarative way.

// main.js (or a plugin file)
import { createApp } from 'vue';
import App from './App.vue';

const app = createApp(App);

// Register a global custom directive called 'focus'
app.directive('focus', {
  mounted(el) {
    el.focus(); // Focus the element when it's mounted
  }
});

// Register a global custom directive called 'highlight'
app.directive('highlight', {
  // Directive hook: called when the bound element's parent component
  // and all its children are mounted.
  mounted(el, binding) {
    el.style.backgroundColor = binding.value || 'yellow';
  },
  // Directive hook: called before the parent component is updated.
  // This is for reactivity if binding.value changes.
  updated(el, binding) {
    el.style.backgroundColor = binding.value || 'yellow';
  }
});

app.mount('#app');

// App.vue (example usage)
<template>
  <div>
    <input v-focus placeholder="This input gets focused on load" />
    <br><br>
    <p v-highlight>This text is highlighted yellow.</p>
    <p v-highlight="'lightblue'">This text is highlighted lightblue.</p>
    <button @click="color = color === 'orange' ? 'lightgreen' : 'orange'">Toggle Highlight Color</button>
    <p v-highlight="color">This text changes highlight color.</p>
  </div>
</template>

<script setup>
import { ref } from 'vue';
const color = ref('orange');
</script>
How it works: This snippet demonstrates defining and using custom directives. `v-focus` automatically focuses an input element when mounted using the `mounted` hook. `v-highlight` sets the background color of an element, accepting an optional argument (e.g., `'lightblue'`) and reacting to changes using the `mounted` and `updated` hooks. Directives provide a powerful way to apply low-level DOM manipulations in a reusable and declarative manner within Vue's ecosystem.

Need help integrating this into your project?

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

Hire DigitalCodeLabs