JAVASCRIPT
Create a Reusable Vue 3 Composable for Click Outside Detection
Develop a custom Vue 3 composable (`useClickOutside`) to detect clicks outside a specific DOM element, useful for dropdowns, modals, and context menus.
// composables/useClickOutside.js
import { ref, onMounted, onUnmounted } from 'vue';
export function useClickOutside(callback) {
const targetRef = ref(null);
const handleClick = (event) => {
if (targetRef.value && !targetRef.value.contains(event.target)) {
callback();
}
};
onMounted(() => {
document.addEventListener('click', handleClick);
});
onUnmounted(() => {
document.removeEventListener('click', handleClick);
});
return { targetRef };
}
// components/MyDropdown.vue
<template>
<div style="position: relative; display: inline-block;">
<button @click="isOpen = !isOpen">Toggle Dropdown</button>
<div v-if="isOpen" ref="targetRef" style="border: 1px solid #ccc; padding: 10px; position: absolute; background: white; z-index: 10;">
Dropdown Content
<p>Click outside to close!</p>
</div>
</div>
</template>
<script setup>
import { ref } from 'vue';
import { useClickOutside } from '../composables/useClickOutside';
const isOpen = ref(false);
const closeDropdown = () => {
isOpen.value = false;
};
const { targetRef } = useClickOutside(closeDropdown);
</script>
How it works: This snippet creates a `useClickOutside` composable, a powerful Vue 3 pattern for reusing stateful logic. It takes a callback function and returns a `targetRef`. The composable automatically adds and removes a global click event listener. When a click occurs outside the element bound to `targetRef`, the provided callback is executed. This is ideal for closing dropdowns, modals, or popovers when the user clicks elsewhere on the page, promoting cleaner and more maintainable UI logic.