cyRefList.ts 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. import {ref, computed, Ref} from 'vue'
  2. import XEUtils from "xe-utils";
  3. import {BizException, ExceptionEnum} from "@/utils/BizException";
  4. import {stringIsBlank} from "@/utils/blank-utils";
  5. declare type CodeType<T> = keyof T & string | ((item: T) => string);
  6. function cyRefList<T = any>(code: CodeType<T>, errMsg: (item: T) => string = () => '请勿重复添加') {
  7. const list: Ref<T[]> = ref([])
  8. const watchFunc: Function[] = []
  9. const codeIsFunction = typeof code === 'function'
  10. const codeKey = computed<string[]>(() => {
  11. return XEUtils.eachAndReturnList(list.value, (item) => {
  12. if (codeIsFunction) {
  13. return code(item)
  14. }
  15. return item[code]
  16. });
  17. });
  18. function sendListening(items: any) {
  19. return new Promise(resolve => {
  20. watchFunc.forEach(item => item(items))
  21. resolve(true)
  22. })
  23. }
  24. const listProxy = {
  25. push: function (...items: T[]) {
  26. const msgList: string[] = []
  27. items.forEach((item: T) => {
  28. let key: string;
  29. if (codeIsFunction) {
  30. key = code(item)
  31. } else {
  32. key = item[code] as string
  33. }
  34. if (stringIsBlank(key)) {
  35. BizException(ExceptionEnum.MESSAGE_ERROR, "没有找到唯一值");
  36. }
  37. if (codeKey.value.includes(key)) {
  38. const msg = errMsg(item)
  39. msgList.push(msg)
  40. }
  41. })
  42. if (msgList.length === 1) {
  43. BizException(ExceptionEnum.MESSAGE_ERROR, msgList[0]);
  44. } else if (msgList.length > 0) {
  45. BizException(ExceptionEnum.MESSAGE_HTML_ERROR, msgList.join("<br/>"));
  46. }
  47. sendListening(items).then(r => {
  48. });
  49. // @ts-ignore
  50. return list.value.push(...items)
  51. },
  52. watchPush: function (cb: (value: T) => void) {
  53. const index = watchFunc.push(cb)
  54. function stop() {
  55. watchFunc.splice(index, 0)
  56. }
  57. return stop
  58. },
  59. delIndex: function (index: number) {
  60. list.value.splice(index, 1);
  61. },
  62. clear: function () {
  63. list.value = []
  64. },
  65. isEmpty() {
  66. return list.value === null || list.value.length === 0
  67. },
  68. emptyError(errorMsg = '请先选择数据') {
  69. if (this.isEmpty()) {
  70. BizException(ExceptionEnum.MESSAGE_ERROR, errorMsg)
  71. }
  72. },
  73. forEach(cb: (item: T, index: number) => void) {
  74. for (let i = 0, len = list.value.length; i < len; i++) {
  75. const item = list.value[i]
  76. cb(item, i)
  77. }
  78. },
  79. eachAndReturnList(iteration: (item: T, index: number) => any) {
  80. return XEUtils.eachAndReturnList(list, iteration)
  81. },
  82. }
  83. return [list, listProxy]
  84. }
  85. export default cyRefList