@zenweb/form
Version:
Zenweb Form module
91 lines (90 loc) • 2.58 kB
JavaScript
import { Field, simple } from '../field.js';
export class Cascader extends Field {
_choices = [];
_max;
_min;
/** 最多可以选择数量 */
max(v) {
this._max = v;
return this;
}
/** 最少选择数量 */
min(v) {
this._min = v;
return this;
}
/**
* 设置选择项
*/
choices(choices) {
for (const c of choices) {
if (typeof c === 'object') {
this._choices.push(c);
}
else {
this._choices.push({ label: c, value: c });
}
}
return this;
}
/**
* 设置选择项,使用指定的 value 和 label
*/
choicesMap(choices, valueKey, labelKey, parentKey) {
/*
// 处理一维结构为树形结构
function each(parentValue: string = null): ChoiceType[] {
return choices.filter(i => i[parentKey] === parentValue).map(i => {
const item: ChoiceType = {
value: i[valueKey],
label: i[labelKey],
};
const children = each(i[valueKey]);
if (children.length) {
item.children = children;
}
return item;
});
}
return this.choices(each());
*/
return this.choices(choices.map(i => ({ value: i[valueKey], label: i[labelKey], parent: i[parentKey] })));
}
/**
* 是否没有设置选择项
*/
isEmpty() {
return this._choices.length === 0;
}
extra() {
return {
choices: this._choices,
};
}
clean(data) {
data = super.clean(data);
if (data === undefined)
return;
data = Array.isArray(data) ? data : [data];
const max = Math.min(this._max || Number.MAX_VALUE, this._choices.length);
if (data.length > max) {
this.fail('form.select.choice-max', { max });
}
if (this._min && data.length < this._min) {
this.fail('form.select.choice-min', { min: this._min });
}
for (const i of data) {
const item = this._choices.find(c => c.value == i);
if (item) {
if (item.disabled) {
this.fail('form.select.choice-disabled', { data: i, label: item.label });
}
}
else {
this.fail('form.select.choice-invalid', { data: i });
}
}
return data;
}
}
export const cascader = simple(Cascader);