123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108 |
- import { ref, computed, Ref } from "vue";
- import XEUtils from "xe-utils";
- import { BizException, ExceptionEnum } from "@/utils/BizException";
- import { stringIsBlank } from "@/utils/blank-utils";
- declare type CodeType<T> = (keyof T & string) | ((item: T) => string);
- function cyRefList<T = any>(
- code: CodeType<T>,
- errMsg: (item: T) => string = () => "请勿重复添加"
- ): [
- Ref<T[]>,
- {
- push: (...items: T[]) => number;
- watchPush: (cb: (value: T) => void) => () => void;
- delIndex: (index: number) => void;
- clear: () => void;
- isEmpty: () => boolean;
- emptyError: (errorMsg?: string) => void;
- forEach: (cb: (item: T, index: number) => void) => void;
- eachAndReturnList: (iteration: (item: T, index: number) => any) => any[];
- },
- ] {
- const list = ref([]) as Ref<T[]>;
- const watchFunc: Function[] = [];
- const codeIsFunction = typeof code === "function";
- const codeKey = computed<string[]>(() => {
- return XEUtils.eachAndReturnList(list.value, item => {
- if (codeIsFunction) {
- return code(item);
- }
- return item[code];
- });
- });
- function sendListening(items: any) {
- return new Promise(resolve => {
- watchFunc.forEach(item => item(items));
- resolve(true);
- });
- }
- const listProxy = {
- push: function (...items: T[]) {
- const msgList: string[] = [];
- items.forEach((item: T) => {
- let key: string;
- if (codeIsFunction) {
- key = code(item);
- } else {
- key = item[code] as string;
- }
- if (stringIsBlank(key)) {
- BizException(ExceptionEnum.MESSAGE_ERROR, "没有找到唯一值");
- }
- if (codeKey.value.includes(key)) {
- const msg = errMsg(item);
- msgList.push(msg);
- }
- });
- if (msgList.length === 1) {
- BizException(ExceptionEnum.MESSAGE_ERROR, msgList[0]);
- } else if (msgList.length > 0) {
- BizException(ExceptionEnum.MESSAGE_HTML_ERROR, msgList.join("<br/>"));
- }
- sendListening(items).then(r => {});
- return list.value.push(...items);
- },
- watchPush: function (cb: (value: T) => void) {
- const index = watchFunc.push(cb);
- function stop() {
- watchFunc.splice(index, 0);
- }
- return stop;
- },
- delIndex: function (index: number) {
- list.value.splice(index, 1);
- },
- clear: function () {
- list.value = [];
- },
- isEmpty() {
- return list.value === null || list.value.length === 0;
- },
- emptyError(errorMsg = "请先选择数据") {
- if (this.isEmpty()) {
- BizException(ExceptionEnum.MESSAGE_ERROR, errorMsg);
- }
- },
- forEach(cb: (item: T, index: number) => void) {
- for (let i = 0, len = list.value.length; i < len; i++) {
- const item = list.value[i];
- cb(item, i);
- }
- },
- eachAndReturnList(iteration: (item: T, index: number) => any) {
- return XEUtils.eachAndReturnList(list, iteration);
- },
- };
- return [list, listProxy];
- }
- export default cyRefList;
|