index.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. // 获取元素宽高
  2. export const getRect = ({ name, onSuccess, instance, multiple }) => {
  3. // 创建一个选择器查询对象
  4. const select = uni.createSelectorQuery().in(instance.proxy);
  5. // 选择指定元素,并获取其矩形信息
  6. select
  7. .select(name)
  8. .boundingClientRect((rect) => {
  9. // 如果rect是一个数组,则返回
  10. if (!rect) return;
  11. if (Array.isArray(rect)) return multiple ? rect : rect[0];
  12. // 如果onSuccess存在,则调用onSuccess函数,并传入rect的高度
  13. onSuccess?.(rect);
  14. })
  15. .exec();
  16. };
  17. //- 小写数字转换成大写, 只处理到[0 ~ 99]
  18. export const numberConvertToUppercase = (num) => {
  19. num = Number(num);
  20. const upperCaseNumber = [
  21. "零",
  22. "一",
  23. "二",
  24. "三",
  25. "四",
  26. "五",
  27. "六",
  28. "七",
  29. "八",
  30. "九",
  31. "十",
  32. "百",
  33. "千",
  34. "万",
  35. "亿",
  36. ];
  37. let length = String(num).length;
  38. if (length == 1) {
  39. return upperCaseNumber[num];
  40. } else if (length == 2) {
  41. if (num == 10) {
  42. return upperCaseNumber[num];
  43. } else if (num > 10 && num < 20) {
  44. return "十" + upperCaseNumber[String(num).charAt(1)];
  45. } else {
  46. return (
  47. upperCaseNumber[String(num).charAt(0)] +
  48. "十" +
  49. upperCaseNumber[String(num).charAt(1)].replace("零", "")
  50. );
  51. }
  52. }
  53. };
  54. // 将扁平数组转为树形结构
  55. export const arrayToTree = ({
  56. list,
  57. id = "id",
  58. pid = "parent_id",
  59. firstId = 1,
  60. }) => {
  61. let res = []; // 存放结果集
  62. let map = {};
  63. // 判断对象是否有某个属性
  64. let getHasOwnProperty = (obj, property) =>
  65. Object.prototype.hasOwnProperty.call(obj, property);
  66. // 边做map存储,边找对应关系
  67. for (const i of list) {
  68. map[i[id]] = {
  69. ...i,
  70. children: getHasOwnProperty(map, i[id]) ? map[i[id]].children : [],
  71. };
  72. const newItem = map[i[id]];
  73. if (i[pid] === firstId) {
  74. res.push(newItem);
  75. } else {
  76. if (!getHasOwnProperty(map, i[pid])) {
  77. map[i[pid]] = {
  78. children: [],
  79. };
  80. }
  81. map[i[pid]].children.push(newItem);
  82. }
  83. }
  84. return res;
  85. };
  86. // 防抖
  87. export const debounce = (fn, delay = 300) => {
  88. let timer = null;
  89. return function (...args) {
  90. if (timer) clearTimeout(timer);
  91. timer = setTimeout(() => {
  92. fn.apply(this, args);
  93. }, delay);
  94. };
  95. };
  96. // 节流
  97. export const throttle = (fn, interval = 300) => {
  98. let lastTime = 0;
  99. return function (...args) {
  100. const now = Date.now();
  101. if (now - lastTime >= interval) {
  102. lastTime = now;
  103. fn.apply(this, args);
  104. }
  105. };
  106. };