Skip to content

Instantly share code, notes, and snippets.

@jackabox
Created September 4, 2019 12:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jackabox/78bec8af44d6eb35e3094e59feedc209 to your computer and use it in GitHub Desktop.
Save jackabox/78bec8af44d6eb35e3094e59feedc209 to your computer and use it in GitHub Desktop.
Click outside of a div or children to be able to trigger an action (close of the div itself)
<template>
<li
v-if="isLoggedIn"
class="user-menu__item relative btn"
@click="showAccountEvent"
v-click-outside="closeAccountEvent"
>
<user-dropdown v-if="showAccount" />
</li>
</template>
<script>
export default {
methods: {
showAccountEvent() {
this.showAccount = true
},
closeAccountEvent() {
this.showAccount = false
}
}
}
</script>
import Vue from 'vue'
// Detect the click outside the element or it's children.
Vue.directive('click-outside', {
bind: function(el, binding, vnode) {
el.clickOutsideEvent = function(event) {
if (!(el == event.target || el.contains(event.target))) {
vnode.context[binding.expression](event)
}
}
document.body.addEventListener('click', el.clickOutsideEvent)
},
unbind: function(el) {
document.body.removeEventListener('click', el.clickOutsideEvent)
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment