提交 | 用户 | 时间
|
e57a89
|
1 |
import Vue from 'vue' |
懒 |
2 |
import { mergeRecursive } from "@/utils/ruoyi"; |
|
3 |
import DictMeta from './DictMeta' |
|
4 |
import DictData from './DictData' |
|
5 |
|
|
6 |
const DEFAULT_DICT_OPTIONS = { |
|
7 |
types: [], |
|
8 |
} |
|
9 |
|
|
10 |
/** |
|
11 |
* @classdesc 字典 |
|
12 |
* @property {Object} label 标签对象,内部属性名为字典类型名称 |
|
13 |
* @property {Object} dict 字段数组,内部属性名为字典类型名称 |
|
14 |
* @property {Array.<DictMeta>} _dictMetas 字典元数据数组 |
|
15 |
*/ |
|
16 |
export default class Dict { |
|
17 |
constructor() { |
|
18 |
this.owner = null |
|
19 |
this.label = {} |
|
20 |
this.type = {} |
|
21 |
} |
|
22 |
|
|
23 |
init(options) { |
|
24 |
if (options instanceof Array) { |
|
25 |
options = { types: options } |
|
26 |
} |
|
27 |
const opts = mergeRecursive(DEFAULT_DICT_OPTIONS, options) |
|
28 |
if (opts.types === undefined) { |
|
29 |
throw new Error('need dict types') |
|
30 |
} |
|
31 |
const ps = [] |
|
32 |
this._dictMetas = opts.types.map(t => DictMeta.parse(t)) |
|
33 |
this._dictMetas.forEach(dictMeta => { |
|
34 |
const type = dictMeta.type |
|
35 |
Vue.set(this.label, type, {}) |
|
36 |
Vue.set(this.type, type, []) |
|
37 |
if (dictMeta.lazy) { |
|
38 |
return |
|
39 |
} |
|
40 |
ps.push(loadDict(this, dictMeta)) |
|
41 |
}) |
|
42 |
return Promise.all(ps) |
|
43 |
} |
|
44 |
|
|
45 |
/** |
|
46 |
* 重新加载字典 |
|
47 |
* @param {String} type 字典类型 |
|
48 |
*/ |
|
49 |
reloadDict(type) { |
|
50 |
const dictMeta = this._dictMetas.find(e => e.type === type) |
|
51 |
if (dictMeta === undefined) { |
|
52 |
return Promise.reject(`the dict meta of ${type} was not found`) |
|
53 |
} |
|
54 |
return loadDict(this, dictMeta) |
|
55 |
} |
|
56 |
} |
|
57 |
|
|
58 |
/** |
|
59 |
* 加载字典 |
|
60 |
* @param {Dict} dict 字典 |
|
61 |
* @param {DictMeta} dictMeta 字典元数据 |
|
62 |
* @returns {Promise} |
|
63 |
*/ |
|
64 |
function loadDict(dict, dictMeta) { |
|
65 |
return dictMeta.request(dictMeta) |
|
66 |
.then(response => { |
|
67 |
const type = dictMeta.type |
|
68 |
let dicts = dictMeta.responseConverter(response, dictMeta) |
|
69 |
if (!(dicts instanceof Array)) { |
|
70 |
console.error('the return of responseConverter must be Array.<DictData>') |
|
71 |
dicts = [] |
|
72 |
} else if (dicts.filter(d => d instanceof DictData).length !== dicts.length) { |
|
73 |
console.error('the type of elements in dicts must be DictData') |
|
74 |
dicts = [] |
|
75 |
} |
|
76 |
dict.type[type].splice(0, Number.MAX_SAFE_INTEGER, ...dicts) |
|
77 |
dicts.forEach(d => { |
|
78 |
Vue.set(dict.label[type], d.value, d.label) |
|
79 |
}) |
|
80 |
return dicts |
|
81 |
}) |
|
82 |
} |