index.ts 800 B

1234567891011121314151617181920212223242526272829303132
  1. import { watch } from 'vue'
  2. import { isClient, useEventListener } from '@vueuse/core'
  3. import { EVENT_CODE } from '@element-plus/constants'
  4. import type { Ref } from 'vue'
  5. type ModalInstance = {
  6. handleClose: () => void
  7. }
  8. const modalStack: ModalInstance[] = []
  9. const closeModal = (e: KeyboardEvent) => {
  10. if (modalStack.length === 0) return
  11. if (e.code === EVENT_CODE.esc) {
  12. e.stopPropagation()
  13. const topModal = modalStack[modalStack.length - 1]
  14. topModal.handleClose()
  15. }
  16. }
  17. export const useModal = (instance: ModalInstance, visibleRef: Ref<boolean>) => {
  18. watch(visibleRef, (val) => {
  19. if (val) {
  20. modalStack.push(instance)
  21. } else {
  22. modalStack.splice(modalStack.indexOf(instance), 1)
  23. }
  24. })
  25. }
  26. if (isClient) useEventListener(document, 'keydown', closeModal)