JAVASCRIPT

Build Custom Vue 3 Directives

Learn to extend Vue 3's core functionality by creating custom directives for direct DOM manipulation, like automatically focusing an input or changing element styles.

<template>
  <div>
    <h2>Custom Directives Example</h2>
    <input v-focus type="text" placeholder="I will be focused on load">
    <br><br>
    <div v-color-on-hover="'blue'" style="padding: 10px; border: 1px solid gray;">
      Hover over me to change color
    </div>
  </div>
</template>

<script setup>
import { onMounted, onUnmounted } from 'vue';

// Local directive v-focus
const vFocus = {
  mounted: (el) => {
    el.focus();
  }
};

// Local directive v-color-on-hover
const vColorOnHover = {
  mounted: (el, binding) => {
    const defaultColor = el.style.backgroundColor;
    const hoverColor = binding.value || 'yellow'; // Use binding value or default

    const mouseEnterHandler = () => {
      el.style.backgroundColor = hoverColor;
    };
    const mouseLeaveHandler = () => {
      el.style.backgroundColor = defaultColor;
    };

    el._mouseEnterHandler = mouseEnterHandler; // Store handlers for cleanup
    el._mouseLeaveHandler = mouseLeaveHandler;

    el.addEventListener('mouseenter', mouseEnterHandler);
    el.addEventListener('mouseleave', mouseLeaveHandler);
  },
  unmounted: (el) => {
    // Clean up event listeners to prevent memory leaks
    if (el._mouseEnterHandler) {
      el.removeEventListener('mouseenter', el._mouseEnterHandler);
    }
    if (el._mouseLeaveHandler) {
      el.removeEventListener('mouseleave', el._mouseLeaveHandler);
    }
  }
};
</script>
How it works: Custom directives in Vue 3 allow you to directly manipulate the DOM. The `vFocus` directive automatically focuses an input field when the component mounts. The `vColorOnHover` directive changes an element's background color on mouse hover, accepting a value (e.g., `'blue'`) from the binding. Directives expose various lifecycle hooks like `mounted` and `unmounted` to control their behavior during the element's lifecycle and perform necessary cleanup to prevent memory leaks.

Need help integrating this into your project?

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

Hire DigitalCodeLabs