Skip to content

Instantly share code, notes, and snippets.

@gelbehexe
Last active June 4, 2021 10:31
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 gelbehexe/624935da744934c9fe7de8dd6416c351 to your computer and use it in GitHub Desktop.
Save gelbehexe/624935da744934c9fe7de8dd6416c351 to your computer and use it in GitHub Desktop.
Vue 3 useClickAway(composition api)
<template>
<div class="bg-gray-200 w-screen min-h-screen h-full py-4">
<div
class="w-full sm:max-w-screen-sm md:max-w-screen-md mx-auto p-6 bg-gray-50 space-y-5"
>
<h1 class="my-2 text-center text-2xl font-bold">
Click Away Demo
</h1>
<a
href="#"
class="underline hover:opacity-75"
@click.prevent="handleTestClick"
>
Link outside - click to toggle yellow background
</a>
<div class="relative">
<a
ref="togglerRef"
href="#"
class="block bg-green-500 hover:bg-opacity-75"
@click.prevent="show = !show"
>
Toggle
</a>
<div
v-if="show"
class="absolute bg-blue-200 w-full text-center p-4"
>
Content to toggle
</div>
</div>
</div>
</div>
</template>
<script>
import { ref } from "vue"
import useClickAway from "@/composition/useClickAway"
export default {
name: "ClickAwayTester",
setup() {
const show = ref(false)
const togglerRef = ref(null)
function handleTestClick(ev) {
ev.target.classList.toggle("bg-yellow-200")
}
useClickAway(togglerRef, () => {
show.value = false
}, () => show.value)
return {
show,
togglerRef,
handleTestClick,
}
},
}
</script>
import { onMounted, onUnmounted } from "vue"
/**
* @param {Ref<HTMLElement>} ref
* @param {Function} action
* @param {Function} condition
*/
export default function useClickAway(ref, action, condition = () => true) {
function clickAwayHandler(ev) {
if (!condition(ev)) {
return
}
if (ref !== null) {
if (!ref || !ref.value || ev.target === ref.value || ref.value.contains(ev.target)) {
return
}
}
action(ev)
}
onMounted(() => {
window.addEventListener("click", clickAwayHandler, true)
})
onUnmounted(() => {
window.removeEventListener("click", clickAwayHandler)
})
}
@gelbehexe
Copy link
Author

Vue 3 useClickAway(composition api)

Here a little example for Vue 3 with composition api for easy adding a reusable clickAway functionality in just a few lines.


Hier ein kleines Beispiel für Vue 3 mit der Composition Api, um mit wenigen Zeilen eine wiederverwendbare ClickAway-Funktion hinzuzufügen.

Codepen

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment