Created
August 14, 2022 02:20
-
-
Save Erefor/1aa0c587bd0a9fc3e5c27683967df413 to your computer and use it in GitHub Desktop.
Vue 3 / Options Api Detect outside click
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 | |
ref="componentRef" | |
class="general-style" | |
> | |
</div> | |
</template> | |
<script> | |
import useDetectOutsideClick from '/useDetectOutsideClick' | |
export default { | |
data(){ | |
return { | |
data: 'hello' | |
} | |
}, | |
mounted(){ | |
useDetectOutsideClick(this.$refs.componentRef, () => { | |
this.data = 'edit hello' | |
}) | |
} | |
} | |
</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 {onBeforeUnmount, onMounted} from 'vue' | |
export default function useDetectOutsideClick(component, callback) { | |
if (!component) return | |
const listener = (event) => { | |
if (event.target !== component.value && event.composedPath().includes(component.value)) { | |
return | |
} | |
if (typeof callback === 'function') { | |
callback() | |
} | |
} | |
onMounted(() => { window.addEventListener('click', listener) }) | |
onBeforeUnmount(() => {window.removeEventListener('click', listener)}) | |
return {listener} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Great. Thanks Much