toast.ts 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /**
  2. * toast 弹窗组件
  3. * 支持 success/error/warning/info 四种状态
  4. * 可配置 duration, position 等参数
  5. */
  6. type ToastType = 'success' | 'error' | 'warning' | 'info'
  7. interface ToastOptions {
  8. type?: ToastType
  9. duration?: number
  10. position?: 'top' | 'middle' | 'bottom'
  11. icon?: 'success' | 'error' | 'none' | 'loading' | 'fail' | 'exception'
  12. message: string
  13. }
  14. export function showToast(options: ToastOptions | string) {
  15. const defaultOptions: ToastOptions = {
  16. type: 'info',
  17. duration: 2000,
  18. position: 'middle',
  19. message: '',
  20. }
  21. const mergedOptions
  22. = typeof options === 'string'
  23. ? { ...defaultOptions, message: options }
  24. : { ...defaultOptions, ...options }
  25. // 映射position到uniapp支持的格式
  26. const positionMap: Record<ToastOptions['position'], 'top' | 'bottom' | 'center'> = {
  27. top: 'top',
  28. middle: 'center',
  29. bottom: 'bottom',
  30. }
  31. // 映射图标类型
  32. const iconMap: Record<
  33. ToastType,
  34. 'success' | 'error' | 'none' | 'loading' | 'fail' | 'exception'
  35. > = {
  36. success: 'success',
  37. error: 'error',
  38. warning: 'fail',
  39. info: 'none',
  40. }
  41. // 调用uni.showToast显示提示
  42. uni.showToast({
  43. title: mergedOptions.message,
  44. duration: mergedOptions.duration,
  45. position: positionMap[mergedOptions.position],
  46. icon: mergedOptions.icon || iconMap[mergedOptions.type],
  47. mask: true,
  48. })
  49. }
  50. export const toast = {
  51. success: (message: string, options?: Omit<ToastOptions, 'type'>) =>
  52. showToast({ ...options, type: 'success', message }),
  53. error: (message: string, options?: Omit<ToastOptions, 'type'>) =>
  54. showToast({ ...options, type: 'error', message }),
  55. warning: (message: string, options?: Omit<ToastOptions, 'type'>) =>
  56. showToast({ ...options, type: 'warning', message }),
  57. info: (message: string, options?: Omit<ToastOptions, 'type'>) =>
  58. showToast({ ...options, type: 'info', message }),
  59. }