Created
June 8, 2020 15:04
-
-
Save CyberAP/14d09a3d1b73035eae110e7de0f62530 to your computer and use it in GitHub Desktop.
Handle clicks outside an element, done via Vue component
This file contains hidden or 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> | |
| <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