ui.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. import { router } from "@/cool";
  2. import type { ClConfirmAction, ClConfirmOptions, ClToastOptions } from "../types";
  3. import { t } from "@/locale";
  4. /**
  5. * UiInstance 类型定义
  6. * - showConfirm: 显示确认弹窗的方法
  7. * - showTips: 显示提示弹窗的方法
  8. */
  9. export type UiInstance = {
  10. /**
  11. * 显示确认弹窗
  12. * @param options ClConfirmOptions 弹窗配置项
  13. */
  14. showConfirm: (options: ClConfirmOptions) => void;
  15. /**
  16. * 显示提示弹窗
  17. * @param message 提示消息
  18. * @param callback 回调函数,参数为用户操作类型
  19. */
  20. showTips: (message: string, callback: (action: ClConfirmAction) => void) => void;
  21. /**
  22. * 显示提示弹窗
  23. * @param options ClToastOptions 弹窗配置项
  24. */
  25. showToast: (options: ClToastOptions) => void;
  26. };
  27. /**
  28. * 存储每个页面对应的 UiInstance 实例
  29. * key: 当前页面路由
  30. * value: UiInstance 实例
  31. */
  32. const list = new Map<string, UiInstance>();
  33. /**
  34. * Ui 类,提供全局弹窗调用能力
  35. */
  36. class Ui {
  37. /**
  38. * 获取当前页面的 UiInstance 实例
  39. * @returns UiInstance | undefined
  40. */
  41. getInstance() {
  42. return list.get(router.path());
  43. }
  44. /**
  45. * 显示确认弹窗
  46. * @param options ClConfirmOptions 弹窗配置项
  47. */
  48. showConfirm(options: ClConfirmOptions): void {
  49. const instance = this.getInstance();
  50. if (instance != null) {
  51. instance.showConfirm(options);
  52. }
  53. }
  54. /**
  55. * 显示提示弹窗
  56. * @param message 提示消息
  57. * @param callback 回调函数
  58. */
  59. showTips(message: string, callback: (action: ClConfirmAction) => void): void {
  60. const instance = this.getInstance();
  61. if (instance != null) {
  62. instance.showTips(message, callback);
  63. }
  64. }
  65. /**
  66. * 显示提示弹窗
  67. * @param options ClToastOptions 弹窗配置项
  68. */
  69. showToast(options: ClToastOptions): void {
  70. const instance = this.getInstance();
  71. if (instance != null) {
  72. instance.showToast(options);
  73. }
  74. }
  75. /**
  76. * 显示加载中弹窗
  77. * @param title 提示内容
  78. * @param mask 是否显示蒙层
  79. */
  80. showLoading(title: string | null = null, mask: boolean | null = null): void {
  81. uni.showLoading({
  82. title: title ?? t("加载中"),
  83. mask: mask ?? true
  84. });
  85. }
  86. /**
  87. * 隐藏加载中弹窗
  88. */
  89. hideLoading(): void {
  90. uni.hideLoading();
  91. }
  92. }
  93. /**
  94. * 获取 Ui 实例(始终返回同一个 Ui 实例)
  95. * @returns Ui
  96. */
  97. const ui = new Ui();
  98. export function useUi() {
  99. return ui;
  100. }
  101. /**
  102. * 注册当前页面的 UiInstance 实例
  103. * @param instance UiInstance
  104. */
  105. export function createUi(instance: UiInstance): void {
  106. list.set(router.path(), instance);
  107. }