usePopup.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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. uni.$emit('cwg-dropdown:close-all')
  40. popupState.value = {
  41. visible: true,
  42. title: options.title || t('Msg.SystemPrompt'),
  43. content: options.content || '',
  44. showCancel: options.showCancel != undefined ? options.showCancel: true,
  45. cancelText: options.cancelText || t('Btn.Cancel'),
  46. confirmText: options.confirmText || t('Btn.Confirm'),
  47. autoClose: options.autoClose || false,
  48. autoCloseDelay: options.autoCloseDelay || 2000,
  49. resolve
  50. }
  51. })
  52. }
  53. const toast = (options: PopupOptions | string = {}): Promise<boolean> => {
  54. const params = typeof options === 'string' ? { content: options } : options
  55. return new Promise((resolve) => {
  56. uni.$emit('cwg-dropdown:close-all')
  57. popupState.value = {
  58. visible: true,
  59. title: params.title || t('Msg.SystemPrompt'),
  60. content: params.content || '',
  61. showCancel: params.showCancel != undefined ? params.showCancel: true,
  62. cancelText: params.cancelText || t('Btn.Cancel'),
  63. confirmText: params.confirmText || t('Btn.Confirm'),
  64. autoClose: true,
  65. autoCloseDelay: params.autoCloseDelay || 2000,
  66. resolve
  67. }
  68. })
  69. }
  70. const close = () => {
  71. if (popupState.value.resolve) {
  72. popupState.value.resolve(false)
  73. popupState.value.resolve = null
  74. }
  75. popupState.value.visible = false
  76. }
  77. const handleConfirm = () => {
  78. if (popupState.value.resolve) {
  79. popupState.value.resolve(true)
  80. popupState.value.resolve = null
  81. }
  82. popupState.value.visible = false
  83. }
  84. return {
  85. popupState,
  86. confirm,
  87. toast,
  88. close,
  89. handleConfirm
  90. }
  91. }