12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697 |
- 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 = () => '请勿重复添加') {
- const list: Ref<T[]> = ref([])
- 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 => {
- });
- // @ts-ignore
- 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
|