usePopup.ts 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. import { ref } from 'vue'
  2. import { useI18n } from 'vue-i18n'
  3. interface PopupOptions {
  4. title?: string
  5. content?: string
  6. cancelText?: string
  7. confirmText?: string
  8. width?: number
  9. showCancel?: boolean
  10. autoClose?: boolean
  11. autoCloseDelay?: number
  12. }
  13. interface PopupState {
  14. visible: boolean
  15. title: string
  16. content: string
  17. cancelText: string
  18. confirmText: string
  19. showCancel: boolean
  20. autoClose: boolean
  21. autoCloseDelay: number
  22. resolve: ((value: boolean) => void) | null
  23. }
  24. const popupState = ref<PopupState>({
  25. visible: false,
  26. title: '',
  27. content: '',
  28. cancelText: '',
  29. confirmText: '',
  30. showCancel: true,
  31. autoClose: false,
  32. autoCloseDelay: 2000,
  33. resolve: null
  34. })
  35. export function usePopup() {
  36. const { t } = useI18n()
  37. const confirm = (options: PopupOptions = {}): Promise<boolean> => {
  38. return new Promise((resolve) => {
  39. popupState.value = {
  40. visible: true,
  41. title: options.title || t('Msg.SystemPrompt'),
  42. content: options.content || '',
  43. showCancel: options.showCancel != undefined ? options.showCancel: true,
  44. cancelText: options.cancelText || t('Btn.Cancel'),
  45. confirmText: options.confirmText || t('Btn.Confirm'),
  46. autoClose: options.autoClose || false,
  47. autoCloseDelay: options.autoCloseDelay || 2000,
  48. resolve
  49. }
  50. })
  51. }
  52. const toast = (options: PopupOptions | string = {}): Promise<boolean> => {
  53. const params = typeof options === 'string' ? { content: options } : options
  54. return new Promise((resolve) => {
  55. popupState.value = {
  56. visible: true,
  57. title: params.title || t('Msg.SystemPrompt'),
  58. content: params.content || '',
  59. showCancel: params.showCancel != undefined ? params.showCancel: true,
  60. cancelText: params.cancelText || t('Btn.Cancel'),
  61. confirmText: params.confirmText || t('Btn.Confirm'),
  62. autoClose: true,
  63. autoCloseDelay: params.autoCloseDelay || 2000,
  64. resolve
  65. }
  66. })
  67. }
  68. const close = () => {
  69. if (popupState.value.resolve) {
  70. popupState.value.resolve(false)
  71. popupState.value.resolve = null
  72. }
  73. popupState.value.visible = false
  74. }
  75. const handleConfirm = () => {
  76. if (popupState.value.resolve) {
  77. popupState.value.resolve(true)
  78. popupState.value.resolve = null
  79. }
  80. popupState.value.visible = false
  81. }
  82. return {
  83. popupState,
  84. confirm,
  85. toast,
  86. close,
  87. handleConfirm
  88. }
  89. }