import {ref, onMounted, onUnmounted, type Ref} from 'vue'
function useClickOutside(
elementRef: Ref<null | HTMLElement>,
isOpen?: Ref<boolean>
) {
const isClickOutside = ref(false)
function handler(e: MouseEvent) {
if (elementRef.value) {
if (!elementRef.value.contains(e.target as HTMLElement)) {
isClickOutside.value = true
if (isOpen) {
if (isOpen.value) isOpen.value = false
}
} else {
isClickOutside.value = false
}
}
}
onMounted(() => {
document.addEventListener('click', handler)
})
onUnmounted(() => {
document.removeEventListener('click', handler)
})
return isClickOutside
}
export default useClickOutside
在 Dropdown.vue 中 使用 useClickOutside.ts
import { ref, watch } from 'vue'
import useClickOutside from '@/hooks/useClickOutside'
interface DropdownProps {
title: string
}
const { title } = defineProps<DropdownProps>()
const isOpen = ref(false)
function toggleIsOpen() {
isOpen.value = !isOpen.value
}
const dropdownRef = ref<null | HTMLElement>(null)
useClickOutside(dropdownRef, isOpen)