-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- 实现了一个新的 useModal 钩子,用于管理模态框的显示和关闭逻辑 - 添加了对 Esc 键关闭模态框的支持 - 在客户端环境下,添加了全局键盘事件监听
- Loading branch information
Showing
1 changed file
with
32 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
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) |