Created
October 22, 2020 10:09
-
-
Save doomkit/fb4f958f47ce8d5f3e0108c13589cff2 to your computer and use it in GitHub Desktop.
Vue 3 ClickOutside directive
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
| 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); | |
| }, | |
| }; |
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 | |
| v-if="show" | |
| v-click-outside="show = false" | |
| > | |
| Shown! | |
| </div> | |
| </template> | |
| <script> | |
| export default { | |
| setup() { | |
| const show = ref(true); | |
| return { show }; | |
| } | |
| }; | |
| </script> |
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
| 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