Skip to content

Instantly share code, notes, and snippets.

@novecentonove
Created June 28, 2021 11:13
Show Gist options
  • Save novecentonove/2d4946f8fe75bc51062c014e5d2d8f95 to your computer and use it in GitHub Desktop.
Save novecentonove/2d4946f8fe75bc51062c014e5d2d8f95 to your computer and use it in GitHub Desktop.
Vue 3 click outside directive
const app = Vue.createApp({ .. })
app.directive("click-outside", {
beforeMount: function (el, binding) {
// Define ourClickEventHandler
const ourClickEventHandler = event => {
if (!el.contains(event.target) && el !== event.target) {
// as we are attaching an click event listern to the document (below)
// ensure the events target is outside the element or a child of it
binding.value(event); // before binding it
}
};
// attached the handler to the element so we can remove it later easily
el.__vueClickEventHandler__ = ourClickEventHandler;
// attaching ourClickEventHandler to a listener on the document here
document.addEventListener("click", ourClickEventHandler);
},
unmounted: function (el) {
// Remove Event Listener
document.removeEventListener("click", el.__vueClickEventHandler__);
}
})
app.mount('#app');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment