Skip to content

Commit

Permalink
feat(hooks): 添加 useModal 钩子以支持模态框功能
Browse files Browse the repository at this point in the history
- 实现了一个新的 useModal 钩子,用于管理模态框的显示和关闭逻辑
- 添加了对 Esc 键关闭模态框的支持
- 在客户端环境下,添加了全局键盘事件监听
  • Loading branch information
liuyunhe committed Oct 31, 2024
1 parent 8775e29 commit 8086ec0
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions src/hooks/useModal.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { watch } from 'vue'
import { isClient, useEventListener } from '@vueuse/core'
import { EVENT_CODE } from '@/constants'

import type { Ref } from 'vue'

type ModalInstance = {
handleClose: () => void
}

const modalStack: ModalInstance[] = []

const closeModal = (e: KeyboardEvent) => {
if (modalStack.length === 0) return
if (e.code === EVENT_CODE.esc) {
e.stopPropagation()
const topModal = modalStack[modalStack.length - 1]
topModal.handleClose()
}
}

export const useModal = (instance: ModalInstance, visibleRef: Ref<boolean>) => {
watch(visibleRef, (val) => {
if (val) {
modalStack.push(instance)
} else {
modalStack.splice(modalStack.indexOf(instance), 1)
}
})
}

if (isClient) useEventListener(document, 'keydown', closeModal)

0 comments on commit 8086ec0

Please sign in to comment.