comTool.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. import { rsaDecrypt } from '@/utils/jsencrypt';
  2. /**
  3. * 显示loading
  4. * @param {String|Object} params title或者options。
  5. */
  6. function loading(params) {
  7. const options = getOptions(params);
  8. uni.showLoading({
  9. title: '加载中',
  10. mask: true, // 是否显示透明蒙层,防止触摸穿透,默认true
  11. ...options,
  12. });
  13. }
  14. /**
  15. * 传入Promise方法自定加loading
  16. * @param {Function}
  17. */
  18. async function dispatch(callback) {
  19. if (callback.constructor.name === 'AsyncFunction') {
  20. // todo callback 拿到的永远是 function,暂无解决方案
  21. // 若方法返回值是promise
  22. try {
  23. loading();
  24. const res = await callback();
  25. uni.hideLoading();
  26. return res;
  27. } catch (e) {
  28. uni.hideLoading();
  29. console.error(e);
  30. }
  31. return;
  32. }
  33. // 函数返回值不是Promise
  34. const res = callback();
  35. return res;
  36. }
  37. /**
  38. * 将11位电话 4-7 变为 *
  39. * @param {String} tel 电话号码
  40. * @param {Boolean} isDecrypt 是否解密电话号码
  41. */
  42. function middleTel(tel = '', isDecrypt) {
  43. let phoneNum = tel;
  44. if (isDecrypt) {
  45. // 需要解密tel
  46. phoneNum = rsaDecrypt(tel);
  47. }
  48. const reg = /^(\d{3})\d{4}(\d{4})$/;
  49. return phoneNum.replace(reg, '$1****$2');
  50. }
  51. /**
  52. * @param {String|Object} params title或者options。
  53. * @return {Object} 返回Object
  54. */
  55. function getOptions(params) {
  56. let options = {};
  57. if (params === undefined || params === null) {
  58. return options;
  59. }
  60. if (params.constructor === String) {
  61. options.title = params;
  62. }
  63. if (params.constructor === Object) {
  64. options = { ...params };
  65. }
  66. return options;
  67. }
  68. /**
  69. * 显示消息提示框
  70. * @param {String|Object} params title或者options。
  71. * title 提示的内容,长度与 icon 取值有关。
  72. * @return {Promises} 返回Promise
  73. */
  74. async function toast(params) {
  75. const options = getOptions(params);
  76. const duration = options.duration || 1000; // 提示的延迟时间,单位毫秒,默认:2000
  77. return new Promise((resolve) => {
  78. uni.showToast({
  79. icon: 'none',
  80. duration,
  81. ...options,
  82. });
  83. setTimeout(() => {
  84. resolve();
  85. }, duration);
  86. });
  87. }
  88. const $c = {
  89. loading,
  90. dispatch,
  91. middleTel,
  92. toast,
  93. };
  94. export default {
  95. install(Vue) {
  96. Vue.prototype.$c = $c;
  97. uni.$c = $c;
  98. },
  99. };