JAVASCRIPT

Vue 3 useClickOutside Composable

Implement a reusable Vue 3 composable to detect clicks outside a specified DOM element, perfect for closing dropdowns, modals, or context menus.

import { onMounted, onUnmounted, ref } from 'vue';

function useClickOutside(elementRef, callback) {
  const handler = (event) => {
    if (elementRef.value && !elementRef.value.contains(event.target)) {
      callback(event);
    }
  };

  onMounted(() => {
    document.addEventListener('click', handler);
  });

  onUnmounted(() => {
    document.removeEventListener('click', handler);
  });
}

// Example Usage in a component:
// <template>
//   <div ref="myElement" style="border: 1px solid blue; padding: 20px;">
//     Click inside me.
//     <button @click="isVisible = !isVisible">Toggle Dropdown</button>
//     <div v-if="isVisible" style="border: 1px solid green; padding: 10px;">
//       Dropdown content
//     </div>
//   </div>
//   <p style="margin-top: 20px;">Click anywhere else on the page to hide the dropdown.</p>
// </template>
//
// <script setup>
// import { ref } from 'vue';
// import useClickOutside from './composables/useClickOutside';
//
// const myElement = ref(null);
// const isVisible = ref(true);
//
// useClickOutside(myElement, () => {
//   if (isVisible.value) {
//     isVisible.value = false;
//     console.log('Clicked outside the element!');
//   }
// });
// </script>

export default useClickOutside;
How it works: The `useClickOutside` composable provides a simple way to detect when a user clicks anywhere on the document *outside* a specific DOM element. It takes a Vue `ref` (linked to a template element) and a callback function. It attaches a global click event listener on `onMounted` and cleans it up on `onUnmounted`. When a click occurs, it checks if the event target is inside the provided element; if not, it executes the callback. This pattern is essential for creating interactive UI components like dropdowns or popovers that close when the user interacts elsewhere.

Need help integrating this into your project?

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

Hire DigitalCodeLabs