feat(Form): add failed event params

This commit is contained in:
陈嘉涵 2020-02-10 15:54:03 +08:00
parent 494e303061
commit cb83240372
3 changed files with 51 additions and 18 deletions

View File

@ -135,19 +135,29 @@ export default createComponent({
} }
}, },
// @exposed-api
validate() { validate() {
if (!this.rules) { return new Promise(resolve => {
return true; if (!this.rules) {
} resolve();
return !this.rules.some(rule => {
if (rule.required && !this.formValue) {
this.validateMessage = rule.message;
return true;
} }
return false; const messages = [];
this.rules.forEach(rule => {
if (rule.required && !this.formValue) {
messages.push(rule.message);
}
});
if (messages.length) {
this.validateMessage = messages[0];
resolve({
name: this.name,
messages,
});
} else {
resolve();
}
}); });
}, },

View File

@ -19,10 +19,20 @@ export default createComponent({
methods: { methods: {
// @exposed-api // @exposed-api
validate() { validate() {
return this.fields.map(item => item.validate()).every(item => item); return new Promise((resolve, reject) => {
Promise.all(this.fields.map(item => item.validate())).then(errors => {
errors = errors.filter(item => item);
if (errors.length) {
reject(errors);
} else {
resolve();
}
});
});
}, },
getFormData() { getValues() {
return this.fields.reduce((form, field) => { return this.fields.reduce((form, field) => {
form[field.name] = field.formValue; form[field.name] = field.formValue;
return form; return form;
@ -32,13 +42,18 @@ export default createComponent({
onSubmit(event) { onSubmit(event) {
event.preventDefault(); event.preventDefault();
const valid = this.validate(); const values = this.getValues();
if (valid) { this.validate()
this.$emit('submit', this.getFormData()); .then(() => {
} else { this.$emit('submit', values);
this.$emit('failed'); })
} .catch(errors => {
this.$emit('failed', {
values,
errors,
});
});
}, },
}, },

View File

@ -126,6 +126,10 @@ module.exports = {
path: 'field', path: 'field',
title: 'Field 输入框', title: 'Field 输入框',
}, },
{
path: 'form',
title: 'Form 表单',
},
{ {
path: 'number-keyboard', path: 'number-keyboard',
title: 'NumberKeyboard 数字键盘', title: 'NumberKeyboard 数字键盘',
@ -461,6 +465,10 @@ module.exports = {
path: 'field', path: 'field',
title: 'Field', title: 'Field',
}, },
{
path: 'form',
title: 'Form',
},
{ {
path: 'number-keyboard', path: 'number-keyboard',
title: 'NumberKeyboard', title: 'NumberKeyboard',