Skip to content

Instantly share code, notes, and snippets.

@spac3unit
Forked from CyberAP/OuterClick.vue
Created March 10, 2021 09:02
Show Gist options
  • Select an option

  • Save spac3unit/463067a57d05672af8e73fb818571c8e to your computer and use it in GitHub Desktop.

Select an option

Save spac3unit/463067a57d05672af8e73fb818571c8e to your computer and use it in GitHub Desktop.
Handle clicks outside an element, done via Vue component
<template>
<div class="outer-click" ref="root">
<slot />
</div>
</template>
<script>
export default {
name: 'OuterClick',
props: {
event: {
type: String,
default: 'click',
},
capture: Boolean,
},
mounted() {
document.addEventListener(this.event, this.onClick, this.capture);
},
beforeDestroy() {
document.removeEventListener(this.event, this.onClick, this.capture);
},
methods: {
onClick(event) {
if (this.$refs.root.contains(event.target)) return;
this.$emit('click', event);
},
}
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment