Skip to content

Vue Custom Directives Explained — Extending HTML

DodaTech Updated 2026-06-28 1 min read

In this tutorial, you will learn about Vue Custom Directives Explained. We cover key concepts, practical examples, and best practices to help you master this topic.

Vue custom directives extend HTML with reusable DOM behavior. Unlike components that create new elements, directives transform existing elements with focused functionality.

What You'll Learn

  • Directive lifecycle hooks
  • Creating local and global directives
  • Passing values, arguments, and modifiers
  • Common use cases (focus, clickOutside, tooltip)
  • Directive composition

Why It Matters

Directives encapsulate DOM manipulation logic that would otherwise clutter component code. Built-in directives like v-model and v-if are implemented the same way.

// directives/vClickOutside.js
export const vClickOutside = {
  mounted(el, binding) {
    el.__clickOutsideHandler = (event) => {
      if (!el.contains(event.target) && el !== event.target) {
        binding.value(event);
      }
    };
    document.addEventListener("click", el.__clickOutsideHandler);
  },
  unmounted(el) {
    document.removeEventListener("click", el.__clickOutsideHandler);
  },
};
<template>
  <div>
    <button @click="showDropdown = !showDropdown">Toggle</button>
    <div v-if="showDropdown" v-click-outside="closeDropdown" class="dropdown">
      <p>Option 1</p>
      <p>Option 2</p>
      <p>Option 3</p>
    </div>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { vClickOutside } from "../directives/vClickOutside";

const showDropdown = ref(false);
function closeDropdown() { showDropdown.value = false; }
</script>

**Expected output:** The dropdown closes when clicking outside of it. The directive handles cleanup on unmount.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro