JAVASCRIPT
Vue 3 Composable for Detecting Clicks Outside an Element
Build a reusable Vue 3 Composition API composable (`useClickOutside`) to detect clicks that occur outside a specified DOM element, perfect for closing modals, dropdowns, or popovers.
// composables/useClickOutside.js
import { ref, onMounted, onUnmounted } from 'vue';
export function useClickOutside(elementRef, callback) {
if (!elementRef || !callback) {
console.warn('useClickOutside requires a ref and a callback function.');
return;
}
const handleClick = (event) => {
if (elementRef.value && !elementRef.value.contains(event.target)) {
callback();
}
};
onMounted(() => {
document.addEventListener('click', handleClick);
});
onUnmounted(() => {
document.removeEventListener('click', handleClick);
});
}
// Usage in a component
// <template>
// <div ref="myElement">
// This content is inside.
// <button @click="isVisible = !isVisible">Toggle</button>
// <div v-if="isVisible" class="dropdown">
// Dropdown content
// </div>
// </div>
// </template>
// <script setup>
// import { ref } from 'vue';
// import { useClickOutside } from './composables/useClickOutside';
// const myElement = ref(null);
// const isVisible = ref(true);
// const closeDropdown = () => {
// if (isVisible.value) {
// isVisible.value = false;
// console.log('Clicked outside! Dropdown closed.');
// }
// };
// useClickOutside(myElement, closeDropdown);
// </script>
How it works: This snippet provides a reusable Vue 3 composable, `useClickOutside`, which simplifies the detection of clicks outside a specific DOM element. It takes a `ref` to the element and a callback function. The composable attaches and detaches a global click event listener, executing the callback only when the click target is outside the referenced element. This pattern is invaluable for UI components like dropdowns, modals, and context menus, enabling them to close automatically when the user interacts elsewhere on the page.