docs/.vitepress/theme/components/extrepo/useDropdown.ts
31 lines · 743 bytes
4 symbols in this file
1import { onMounted, onUnmounted, ref } from 'vue'
2
3export function useDropdown() {
4 const rootRef = ref<HTMLElement>()
5 const open = ref(false)
6
7 function toggle() {
8 open.value = !open.value
9 }
10
11 function onDocClick(e: MouseEvent) {
12 if (rootRef.value && !rootRef.value.contains(e.target as Node)) {
13 open.value = false
14 }
15 }
16
17 function onKey(e: KeyboardEvent) {
18 if (e.key === 'Escape') open.value = false
19 }
20
21 onMounted(() => {
22 document.addEventListener('click', onDocClick, true)
23 document.addEventListener('keydown', onKey)
24 })
25 onUnmounted(() => {
26 document.removeEventListener('click', onDocClick, true)
27 document.removeEventListener('keydown', onKey)
28 })
29
30 return { rootRef, open, toggle }
31}