useToast.js 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. import { ref } from "vue";
  2. /**
  3. * opt object | string
  4. * to_url object | string
  5. * 例:
  6. * this.Tips('/pages/test/test'); 跳转不提示
  7. * this.Tips({title:'提示'},'/pages/test/test'); 提示并跳转
  8. * this.Tips({title:'提示'},{tab:1,url:'/pages/index/index'}); 提示并跳转值table上
  9. * tab=1 一定时间后跳转至 table上
  10. * tab=2 一定时间后跳转至非 table上
  11. * tab=3 一定时间后返回上页面
  12. * tab=4 关闭所有页面跳转至非table上
  13. * tab=5 关闭当前页面跳转至table上
  14. */
  15. export function useToast() {
  16. // 提示标题
  17. const tipTitle = ref("");
  18. // 提示图标
  19. const tipIcon = ref("none");
  20. // 提示持续时间
  21. const tipEndtime = ref(2000);
  22. /**
  23. * Tips - 显示提示并可按需跳转页面
  24. * @param {Object|string} opt 提示配置或直接为跳转路径
  25. * @param {Object|string|Function} to_url 跳转配置、路径或回调
  26. */
  27. function Toast(opt, to_url) {
  28. console.log("Toast", opt, to_url);
  29. // 如果第一个参数是字符串,视为跳转路径
  30. if (typeof opt == "string") {
  31. to_url = opt;
  32. opt = {};
  33. }
  34. // 提示内容
  35. tipTitle.value = opt.title || "";
  36. // 图标
  37. tipIcon.value = opt.icon || "none";
  38. // 持续时间
  39. tipEndtime.value = opt.endtime || 1000;
  40. // 接口调用成功的回调函数
  41. let success = opt.success;
  42. // 显示提示
  43. if (tipTitle.value)
  44. uni.showToast({
  45. title: tipTitle.value,
  46. icon: tipIcon.value,
  47. duration: tipEndtime.value,
  48. success,
  49. });
  50. // 跳转逻辑
  51. if (to_url != undefined) {
  52. if (typeof to_url == "object") {
  53. // 对象方式配置跳转
  54. let tab = to_url.tab || 1,
  55. url = to_url.url || "";
  56. console.log('tab', tab)
  57. switch (tab) {
  58. case 1:
  59. // 一定时间后跳转至 table
  60. setTimeout(() => uni.switchTab({ url }), tipEndtime.value);
  61. break;
  62. case 2:
  63. // 跳转至非table页面
  64. setTimeout(() => uni.navigateTo({ url }), tipEndtime.value);
  65. break;
  66. case 3:
  67. // 返回上一个页面
  68. setTimeout(() => {
  69. // #ifndef H5
  70. uni.navigateBack({ delta: 1 });
  71. // #endif
  72. // #ifdef H5
  73. history.back();
  74. // #endif
  75. }, tipEndtime.value);
  76. break;
  77. case 4:
  78. // 关闭所有页面跳转到非 tab 页面
  79. setTimeout(() => uni.reLaunch({ url }), tipEndtime.value);
  80. break;
  81. case 5:
  82. // 关闭当前页面跳转到非 tab 页面
  83. setTimeout(() => uni.redirectTo({ url }), tipEndtime.value);
  84. break;
  85. }
  86. } else if (typeof to_url == "function") {
  87. // 回调函数
  88. setTimeout(() => to_url && to_url(), tipEndtime.value);
  89. } else {
  90. // 普通路径跳转
  91. setTimeout(
  92. () => uni.navigateTo({ url: to_url }),
  93. tipTitle.value ? tipEndtime.value : 0
  94. );
  95. }
  96. }
  97. }
  98. // 导出响应式数据和方法
  99. return {
  100. tipTitle,
  101. tipIcon,
  102. tipEndtime,
  103. Toast
  104. };
  105. }