@egova/components
Version:
components
144 lines (128 loc) • 4.02 kB
text/typescript
import {
Component,
component,
config,
provide,
watch
} from "@egova/flagwind-web";
export function oneOf(value: any, validList: Array<any>) {
for (let i = 0; i < validList.length; i++) {
if (value === validList[i]) {
return true;
}
}
return false;
}
({
name: "iForm",
template: require("./index.html")
})
export default class FormComponent extends Component {
public prefixCls: string = "ivu-form";
({ type: Object })
public model?: Object;
({ type: Object })
public rules?: Object;
({ type: Number })
public labelWidth?: Number;
({
validator: (value: any) => {
return oneOf(value, ["left", "right", "top"]);
},
default: "right"
})
public labelPosition!: string;
({ type: Boolean, default: false })
public inline!: boolean;
({ type: Boolean, default: true })
public showMessage!: boolean;
({
validator: (value: any) => {
return oneOf(value, ["on", "off"]);
},
default: "off"
})
public autocomplete!: string;
({ type: Boolean, default: false })
public hideRequiredMark!: boolean;
({ type: [Boolean, String], default: false })
public labelColon!: boolean | string;
({ type: Boolean, default: false })
public disabled!: boolean;
()
public formInstance: any = this;
public fields: Array<any> = [];
public get classes() {
return [
`${this.prefixCls}`,
`${this.prefixCls}-label-${this.labelPosition}`,
{
[`${this.prefixCls}-inline`]: this.inline,
[`${this.prefixCls}-hide-required-mark`]: this.hideRequiredMark
}
];
}
public get colon() {
let colon = "";
if (this.labelColon) {
colon =
typeof this.labelColon === "boolean" ? ":" : this.labelColon;
}
return colon;
}
public resetFields() {
this.fields.forEach(field => {
field.resetField();
});
}
public validate(callback: Function | null = null) {
return new Promise(resolve => {
let valid = true;
let count = 0;
// fields 为空需要返回promise
if (this.fields.length === 0) {
resolve(valid);
if (typeof callback === "function") {
callback(valid);
}
}
this.fields.forEach(field => {
field.validate("", (errors: any) => {
if (errors) {
valid = false;
}
if (++count === this.fields.length) {
// all finish
resolve(valid);
if (typeof callback === "function") {
callback(valid);
}
}
});
});
});
}
public validateField(prop: string, cb: any) {
const field = this.fields.filter(field => field.prop === prop)[0];
if (!field) {
throw new Error(
"[iView warn]: must call validateField with valid prop string!"
);
}
field.validate("", cb);
}
("rules")
public onRulesChange() {
this.validate();
}
public created() {
this.$on("on-form-item-add", (field: any) => {
if (field) this.fields.push(field);
return false;
});
this.$on("on-form-item-remove", (field: any) => {
if (field.prop) this.fields.splice(this.fields.indexOf(field), 1);
return false;
});
}
}