JAVASCRIPT

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

Learn how to create a reusable Vue 3 custom directive (`v-click-outside`) to detect clicks outside an element, perfect for closing dropdowns or modals.

// directives/click-outside.js
const clickOutside = {
  mounted(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__);
  },
};

export default clickOutside;

// In your component:
/*
<template>
  <div v-click-outside="handleClickOutside" class="my-dropdown">
    <button @click="isOpen = !isOpen">Toggle Dropdown</button>
    <div v-if="isOpen" class="dropdown-content">
      <p>Dropdown content here</p>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import vClickOutside from '@/directives/click-outside'; // Adjust path as needed

const isOpen = ref(false);

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

<style scoped>
.my-dropdown {
  position: relative;
  display: inline-block;
  border: 1px solid #ccc;
  padding: 10px;
}
.dropdown-content {
  position: absolute;
  background: white;
  border: 1px solid #eee;
  padding: 10px;
  margin-top: 5px;
  z-index: 10;
}
</style>
*/
How it works: This Vue 3 custom directive, `v-click-outside`, provides a simple way to detect clicks occurring outside of the element it's applied to. It attaches a global click event listener to the document when the component mounts. When a click occurs, it checks if the click target is the element itself or any of its children. If not, the provided callback function (passed as the directive's value) is executed. The event listener is properly removed when the component unmounts 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