Created
January 30, 2024 09:41
-
-
Save justsomexanda/b8f7156f159fb942a0ea4033dee6d771 to your computer and use it in GitHub Desktop.
Vue 3 simple clicked outside directive
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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