Created
September 4, 2019 12:07
-
-
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)
This file contains 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
<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> |
This file contains 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
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