JAVASCRIPT

Implementing a v-click-outside Custom Directive in Vue 3

Create a custom `v-click-outside` directive in Vue 3 to detect clicks outside a specific element, perfect for closing dropdowns, modals, or context menus.

// src/directives/click-outside.js
export default {
  beforeMount(el, binding) {
    el.__ClickOutsideHandler__ = (event) => {
      if (!(el === event.target || el.contains(event.target))) {
        binding.value(event);
      }
    };
    document.addEventListener('click', el.__ClickOutsideHandler__);
  },
  unmounted(el) {
    document.removeEventListener('click', el.__ClickOutsideHandler__);
    delete el.__ClickOutsideHandler__;
  },
};

// src/main.js (or wherever you register global directives)
import { createApp } from 'vue';
import App from './App.vue';
import ClickOutsideDirective from './directives/click-outside';

const app = createApp(App);
app.directive('click-outside', ClickOutsideDirective);
app.mount('#app');

// src/App.vue
<script setup>
import { ref } from 'vue';

const showDropdown = ref(false);

const closeDropdown = () => {
  console.log('Clicked outside dropdown!');
  showDropdown.value = false;
};
</script>

<template>
  <div>
    <h1>Click Outside Directive</h1>
    <button @click="showDropdown = !showDropdown">Toggle Dropdown</button>

    <div v-if="showDropdown" v-click-outside="closeDropdown" style="border: 1px solid #ccc; padding: 20px; margin-top: 10px; position: absolute; background-color: white;">
      <p>This is a dropdown menu.</p>
      <button>Item 1</button>
      <button>Item 2</button>
    </div>
  </div>
</template>
How it works: This snippet details the creation and usage of a custom `v-click-outside` directive in Vue 3. The directive is defined with `beforeMount` and `unmounted` lifecycle hooks. In `beforeMount`, it attaches a global click event listener to the document. This listener checks if the click occurred outside the element to which the directive is bound (`el`). If it did, the function provided as the directive's value (`binding.value`) is executed. In `unmounted`, the event listener is properly removed to prevent memory leaks. This directive is highly useful for implementing UI components like dropdowns, modals, or context menus that should close when a user clicks anywhere outside of them.

Need help integrating this into your project?

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

Hire DigitalCodeLabs