Vue.js course ยท Module 14: Directives & Plugins

Advanced Directives

2 min read ยท
In this lesson4

In NOVA LAB, advanced interface systems require sophisticated directives. Let's explore three popular patterns: v-click-outside, v-tooltip, and v-intersection.

v-click-outside

Detecting clicks outside an element - ideal for closing menus, dropdowns, and modals:

const vClickOutside = {
  mounted(el, binding) {
    el._clickOutside = (event) => {
      if (!el.contains(event.target)) {
        binding.value(event)
      }
    }
    document.addEventListener('click', el._clickOutside)
  },
  unmounted(el) {
    document.removeEventListener('click', el._clickOutside)
  }
}

Usage:

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

const menuOpen = ref(false)

const vClickOutside = {
  mounted(el, binding) {
    el._clickOutside = (event) => {
      if (!el.contains(event.target)) {
        binding.value(event)
      }
    }
    document.addEventListener('click', el._clickOutside)
  },
  unmounted(el) {
    document.removeEventListener('click', el._clickOutside)
  }
}
</script>

<template>
  <div v-click-outside="() => menuOpen = false">
    <button @click="menuOpen = !menuOpen">Menu</button>
    <ul v-if="menuOpen">
      <li>Option 1</li>
      <li>Option 2</li>
    </ul>
  </div>
</template>

Important: In the unmounted hook, we remove the listener to avoid memory leaks. We store the handler reference on the element (el._clickOutside).

v-tooltip

A simple tooltip displayed on mouse hover:

const vTooltip = {
  mounted(el, binding) {
    const tooltip = document.createElement('div')
    tooltip.className = 'v-tooltip'
    tooltip.textContent = binding.value
    tooltip.style.cssText = `
      position: absolute; background: #333; color: white;
      padding: 6px 12px; border-radius: 6px; font-size: 12px;
      pointer-events: none; opacity: 0; transition: opacity 0.2s;
      z-index: 9999;
    `

    el.style.position = 'relative'
    el.appendChild(tooltip)

    el._showTooltip = () => { tooltip.style.opacity = '1' }
    el._hideTooltip = () => { tooltip.style.opacity = '0' }

    el.addEventListener('mouseenter', el._showTooltip)
    el.addEventListener('mouseleave', el._hideTooltip)
  },
  updated(el, binding) {
    const tooltip = el.querySelector('.v-tooltip')
    if (tooltip) tooltip.textContent = binding.value
  },
  unmounted(el) {
    el.removeEventListener('mouseenter', el._showTooltip)
    el.removeEventListener('mouseleave', el._hideTooltip)
  }
}

v-intersection (Intersection Observer)

Detecting when an element appears in the viewport - ideal for lazy loading and entrance animations:

const vIntersection = {
  mounted(el, binding) {
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach(entry => {
          if (entry.isIntersecting) {
            binding.value(entry)
            if (binding.modifiers.once) {
              observer.unobserve(el)
            }
          }
        })
      },
      { threshold: binding.arg ? parseFloat(binding.arg) : 0.1 }
    )

    el._observer = observer
    observer.observe(el)
  },
  unmounted(el) {
    if (el._observer) {
      el._observer.disconnect()
    }
  }
}

Usage:

<template>
  <div v-intersection.once="onVisible">
    Will appear when the element is visible
  </div>
</template>

Cleanup - The Golden Rule of Directives

Every listener, observer, or timer added in mounted MUST be removed in unmounted. Otherwise, memory leaks will occur.

Pattern:

  1. In mounted - add the handler and store the reference on el
  2. In unmounted - remove the handler using the stored reference
Code for this lesson: App.vue
<script setup>
import { ref } from 'vue'

// v-click-outside
const vClickOutside = {
  mounted(el, binding) {
    el._clickOutside = (event) => {
      if (!el.contains(event.target)) {
        binding.value(event)
      }
    }
    document.addEventListener('click', el._clickOutside)
  },
  unmounted(el) {
    document.removeEventListener('click', el._clickOutside)
  }
}

// v-tooltip (simplified)
const vTooltip = {
  mounted(el, binding) {
    el.style.position = 'relative'
    el.style.cursor = 'pointer'
    const tip = document.createElement('span')
    tip.textContent = binding.value
    tip.style.cssText =
      'position:absolute;bottom:110%;left:50%;transform:translateX(-50%);' +
      'background:#333;color:#00ff88;padding:4px 10px;border-radius:4px;' +
      'font-size:12px;white-space:nowrap;opacity:0;transition:opacity 0.2s;' +
      'pointer-events:none;z-index:100;'
    el.appendChild(tip)
    el._tipShow = () => { tip.style.opacity = '1' }
    el._tipHide = () => { tip.style.opacity = '0' }
    el.addEventListener('mouseenter', el._tipShow)
    el.addEventListener('mouseleave', el._tipHide)
  },
  unmounted(el) {
    el.removeEventListener('mouseenter', el._tipShow)
    el.removeEventListener('mouseleave', el._tipHide)
  }
}

const menuOpen = ref(false)
const items = ref([
  { id: 1, visible: false, label: 'Navigation panel' },
  { id: 2, visible: false, label: 'Diagnostics panel' },
  { id: 3, visible: false, label: 'Communications panel' }
])
</script>

<template>
  <div class="nova-lab">
    <h1>Advanced directives</h1>

    <section class="section">
      <h2>v-click-outside</h2>
      <div v-click-outside="() => menuOpen = false" class="menu-wrapper">
        <button @click.stop="menuOpen = !menuOpen" class="btn">
          {{ menuOpen ? 'Close menu' : 'Open menu' }}
        </button>
        <ul v-if="menuOpen" class="dropdown">
          <li>Navigation</li>
          <li>Diagnostics</li>
          <li>Communication</li>
          <li>Systems</li>
        </ul>
      </div>
      <p class="hint">Click outside the menu to close it</p>
    </section>

    <section class="section">
      <h2>v-tooltip</h2>
      <div class="tooltip-row">
        <button v-tooltip="'Open navigation panel'" class="btn">NAV</button>
        <button v-tooltip="'Systems diagnostics'" class="btn cyan">DIAG</button>
        <button v-tooltip="'Communication system'" class="btn red">COM</button>
      </div>
      <p class="hint">Hover over the buttons</p>
    </section>

    <section class="section">
      <h2>Cleanup - the golden rule</h2>
      <p>Every listener added in mounted() MUST be removed in unmounted().</p>
      <p>Pattern: save a reference on el (e.g. el._handler), remove it in unmounted.</p>
    </section>
  </div>
</template>

<style scoped>
.nova-lab {
  background: #0a0e27;
  color: #c0c0c0;
  min-height: 100vh;
  padding: 20px;
  font-family: monospace;
}
h1 { color: #00ff88; margin-bottom: 20px; }
h2 { color: #00b4d8; font-size: 16px; margin-bottom: 10px; }
.section {
  background: rgba(0, 180, 216, 0.05);
  border: 1px solid rgba(0, 180, 216, 0.2);
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 15px;
}
.btn {
  background: rgba(0, 255, 136, 0.15);
  color: #00ff88;
  border: 1px solid #00ff88;
  padding: 8px 16px;
  border-radius: 6px;
  cursor: pointer;
  font-family: monospace;
}
.btn.cyan { color: #00b4d8; border-color: #00b4d8; background: rgba(0,180,216,0.15); }
.btn.red { color: #e74c3c; border-color: #e74c3c; background: rgba(231,76,60,0.15); }
.menu-wrapper { position: relative; display: inline-block; }
.dropdown {
  position: absolute; top: 100%; left: 0;
  background: #1a1e37; border: 1px solid #00ff88;
  border-radius: 6px; list-style: none;
  padding: 0; margin: 4px 0; min-width: 160px; z-index: 10;
}
.dropdown li {
  padding: 8px 16px; cursor: pointer;
}
.dropdown li:hover { background: rgba(0,255,136,0.1); }
.tooltip-row { display: flex; gap: 12px; }
.hint { color: #666; font-size: 12px; margin-top: 8px; }
</style>

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. Where should the event listener be added in the v-click-outside directive?

  2. 2. Why should event listeners be removed in the unmounted hook?

Hands-on tasks in the game

  • Code editor

    Add a listener on document in mounted, check el.contains(event.target), remove it in unmounted.

  • Vertical ordering

    Arrange the steps of the directive cleanup pattern in the correct order:

  • Click in order

    Arrange the condition that checks whether a click occurred outside the element:

  • Code editor

    Create a directive that adds a tooltip to an element on mouse hover.

  1. QuestionThe v-click-outside directive
  2. QuestionCleanup in directives
  3. Coding taskPractice: v-click-outside
  4. Put in orderDirective cleanup pattern
  5. Click in orderChecking click outside the element
  6. Coding taskPractice: Tooltip Directive

Useful articles