UNPKG

@egova/components

Version:

components

144 lines (128 loc) 4.02 kB
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; } @component({ name: "iForm", template: require("./index.html") }) export default class FormComponent extends Component { public prefixCls: string = "ivu-form"; @config({ type: Object }) public model?: Object; @config({ type: Object }) public rules?: Object; @config({ type: Number }) public labelWidth?: Number; @config({ validator: (value: any) => { return oneOf(value, ["left", "right", "top"]); }, default: "right" }) public labelPosition!: string; @config({ type: Boolean, default: false }) public inline!: boolean; @config({ type: Boolean, default: true }) public showMessage!: boolean; @config({ validator: (value: any) => { return oneOf(value, ["on", "off"]); }, default: "off" }) public autocomplete!: string; @config({ type: Boolean, default: false }) public hideRequiredMark!: boolean; @config({ type: [Boolean, String], default: false }) public labelColon!: boolean | string; @config({ type: Boolean, default: false }) public disabled!: boolean; @provide() 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); } @watch("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; }); } }