Skip to content

Instantly share code, notes, and snippets.

@justsomexanda
Created January 30, 2024 09:41
Show Gist options
  • Save justsomexanda/b8f7156f159fb942a0ea4033dee6d771 to your computer and use it in GitHub Desktop.
Save justsomexanda/b8f7156f159fb942a0ea4033dee6d771 to your computer and use it in GitHub Desktop.
Vue 3 simple clicked outside directive
app.directive('click-outside', {
mounted(el, binding) {
setTimeout(() => {
const clickHandler = (e) => {
if (window[JSON.stringify(el)]) {
return
}
window[JSON.stringify(el)] = true
if (!el.contains(e.target) && !e.target.classList.contains(binding.arg)) {
binding.value()
}
setTimeout(() => {
delete window[JSON.stringify(el)]
}, 200)
}
document.body.addEventListener('click', clickHandler)
// recognize unmounting
el.addEventListener('DOMNodeRemoved', () => {
delete window[JSON.stringify(el)]
document.body.removeEventListener('click', clickHandler)
})
}, 10);
},
})
# Example
<div v-click-outside="() => modal_show_settings = false" />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment