| | |
| | | |
| | | <template> |
| | | <view class="c-form-item"> |
| | | <view class="c-form-item-label"> |
| | | <text |
| | | class="required" |
| | | v-if="required" |
| | | >*</text> |
| | | <text>{{label || name}}</text> |
| | | </view> |
| | | <slot |
| | | :value="formData[name]" |
| | | :onChange="evt=>onChange(evt)" |
| | | /> |
| | | <slot :itemData="itemData" /> |
| | | </view> |
| | | </template> |
| | | |
| | |
| | | formData: Object, |
| | | }, |
| | | data() { |
| | | return {}; |
| | | return { |
| | | error: false, |
| | | }; |
| | | }, |
| | | computed: { |
| | | itemData() { |
| | | return { |
| | | formData: this.formData, |
| | | name: this.name, |
| | | label: this.label, |
| | | required: this.isRequired, |
| | | error: this.error, |
| | | onChange: (evt) => this.onChange(evt), |
| | | }; |
| | | }, |
| | | isRequired() { |
| | | if (this.required) { |
| | | return true; |
| | | } else { |
| | | if (!this.rules || this.rules.length === 0) { |
| | | return false; |
| | | } else if (this.rules.length > 0) { |
| | | for (let rule of this.rules) { |
| | | if (rule.required) { |
| | | return true; |
| | | } |
| | | } |
| | | return false; |
| | | } |
| | | } |
| | | }, |
| | | }, |
| | | methods: { |
| | | onChange(evt) { |
| | |
| | | // 未设置验证 |
| | | if (!this.required && !this.rules) { |
| | | this.formData.$regItemValidator(this.name, () => { |
| | | this.error = false; |
| | | return Promise.resolve({ |
| | | name: this.name, |
| | | passed: true, |
| | | }); |
| | | }); |
| | | } else { |
| | | // 验证规则 |
| | | const descriptor = this.rules || []; |
| | | if (this.required) { |
| | | descriptor.unshift({ |
| | |
| | | const validator = new Schema({ |
| | | [this.name]: descriptor, |
| | | }); |
| | | validator.messages(validateMsgs); // 自定义验证消息 |
| | | // 汉化通用验证消息 |
| | | validator.messages(validateMsgs); |
| | | // 注册验证 |
| | | let errTimer = null; |
| | | this.formData.$regItemValidator(this.name, () => { |
| | | return validator |
| | | .validate({ |
| | |
| | | }) |
| | | .then( |
| | | (res) => { |
| | | this.error = false; |
| | | return { |
| | | name: this.name, |
| | | passed: true, |
| | | }; |
| | | }, |
| | | ({ errors, fields }) => { |
| | | this.error = true; |
| | | clearTimeout(errTimer); |
| | | errTimer = setTimeout(() => { |
| | | this.error = false; |
| | | }, 5000); |
| | | return { |
| | | name: this.name, |
| | | passed: false, |