Skip to content

Instantly share code, notes, and snippets.

@DesignHhuang
Created September 28, 2023 10:49
Show Gist options
  • Save DesignHhuang/c508460404920024663c6713e2affec2 to your computer and use it in GitHub Desktop.
Save DesignHhuang/c508460404920024663c6713e2affec2 to your computer and use it in GitHub Desktop.
useOnClickOutside
import { onMounted, onUnmounted } from 'vue';
export const useOnClickOutside = (ref = null, callback = () => {}) => {
function handleClickOutside(event) {
if (ref.value && !ref.value.contains(event.target)) {
callback()
}
}
onMounted(() => {
document.addEventListener('mousedown', handleClickOutside);
})
onUnmounted(() => {
document.removeEventListener('mousedown', handleClickOutside);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment