Skip to content

Instantly share code, notes, and snippets.

@doomkit
Created October 22, 2020 10:09
Show Gist options
  • Select an option

  • Save doomkit/fb4f958f47ce8d5f3e0108c13589cff2 to your computer and use it in GitHub Desktop.

Select an option

Save doomkit/fb4f958f47ce8d5f3e0108c13589cff2 to your computer and use it in GitHub Desktop.
Vue 3 ClickOutside directive
export const ClickOutsideDirective = {
beforeMount(el, binding) {
el.clickOutsideEvent = function(event) {
if (!(el == event.target || el.contains(event.target))) binding.value();
};
document.body.addEventListener('click', el.clickOutsideEvent);
},
unmounted(el) {
document.body.removeEventListener('click', el.clickOutsideEvent);
},
};
<template>
<div
v-if="show"
v-click-outside="show = false"
>
Shown!
</div>
</template>
<script>
export default {
setup() {
const show = ref(true);
return { show };
}
};
</script>
import { ClickOutsideDirective } from './directives/click-outside';
// ...
const app = createApp(App);
app.directive('click-outside', ClickOutsideDirective);
// ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment