utils.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*
  2. * @Autor: hlb
  3. * @Date: 1970-01-01 08:00:00
  4. * @LastEditors: hlb
  5. * @LastEditTime: 2020-11-25 18:37:34
  6. * @description: 工具
  7. */
  8. import toPinyin from "./toPinyin";
  9. /**
  10. * 根据拼音首字母筛选排序分组
  11. * @param {Array} arr 原数组
  12. * @param {String} key 原数组需要筛选的字段
  13. * @returns {Array} 返回一个[{name: A,value: []}] 格式的二维数组
  14. */
  15. export function getGroupByPinyin(arr, key = 'name') {
  16. if (!arr) return
  17. // 获取A-Z字母数组
  18. let keys = [...Array(26).keys()].map((i) => String.fromCharCode(i + 65));
  19. arr = arr.map((n) => ({
  20. ...n,
  21. py: toPinyin.chineseToInitials(
  22. toPinyin.chineseToPinYin(n[key].substr(0, 1))
  23. ),
  24. }));
  25. let group = [];
  26. for (const i of keys) {
  27. // 新数组一级结构,可自行修改
  28. let item = {
  29. name: i,
  30. value: [],
  31. };
  32. for (const j of arr) {
  33. if (j.py === i) {
  34. item.value.push(j);
  35. }
  36. }
  37. if (item.value.length > 0) {
  38. item.value.sort((a, b) => a[key].localeCompare(b[key]));
  39. group.push(item);
  40. }
  41. }
  42. return group;
  43. }
  44. /**
  45. * 初始化 var barcodeModel = uni.requireNativePlugin("iData-BarcodePlugin-BarcodeModule")
  46. * @param {*} onScan
  47. * @returns
  48. */
  49. export function initBarcodeModule() {
  50. var barcodeModel = uni.requireNativePlugin("iData-BarcodePlugin-BarcodeModule")
  51. barcodeModel.initScan((ret) => {
  52. console.log('initBarcodeModule', ret);
  53. });
  54. return barcodeModel
  55. }
  56. /**
  57. * 页面监听event事件,建议在页面onLoad方法里调用
  58. * @param {*} payload
  59. * @returns
  60. */
  61. export function useGlobalEvent(onScan) {
  62. if (typeof onScan !== 'function') {
  63. throw new Error('onScan 必须是函数');
  64. }
  65. let barcodeModel = initBarcodeModule()
  66. //页面监听event事件,建议在页面onLoad方法里调用
  67. var globalEvent = uni.requireNativePlugin('globalEvent');
  68. globalEvent.addEventListener('iDataBarcodeEvent', (e) => {
  69. onScan(e);
  70. });
  71. return () => {
  72. globalEvent.removeEventListener('iDataBarcodeEvent', onScan);
  73. barcodeModel.closeScan((ret) => {});
  74. };
  75. }