我很难弄清楚Promises
. 我正在使用Vue
和vee-validate
库,它允许通过以下方式手动验证表单:
this.$validator.validate()
但是,当我尝试使用它时,我得到了奇怪的行为:
async isFormValid() {
return await this.$validator.validate();
},
每当我提交有错误的表单时,表单都会发送 AJAX 请求:
onApprove() {
if (!that.isFormValid) {
return false;
}
$.ajax({
...
});
return false; // Modal never closes unless AJAX is successful.
},
此外,我尝试了以下构造:
onApprove() {
this.$validator.validate().then(result => {
if(result) {
$.ajax({
...
});
}
return false; // Modal never closes unless AJAX is successful.
});
},
但这也不起作用。我通过这样做找到了解决方法:
isFormValid() {
this.$validator.validate();
return Object.keys(this.fields).every(key => this.fields[key].valid);
},
但是,如果有人能解释我对“承诺”的误解,那就太好了。
编辑
完整的 onApprove 示例(无论验证如何,始终返回 true:
onApprove() {
that.$validator.validate().then(result => {
if (result) {
$.ajax({
url: '/settings/user_management_add_user', method: 'POST', data: {
csrfmiddlewaretoken: that.csrfToken, password: that.password, user: JSON.stringify(that.users[that.activeUserRow]),
}, success() {
$('#modify_user_modal').modal('hide');
that.showToast('check icon', gettext('User created'));
that.activeUserRow = undefined;
that.initialQuery();
}, error(data) {
that.showToast('remove icon', gettext('User could not be created'));
if (data.responseText && data.responseText.length < 20) {
that.showToast('remove icon', data.responseText);
}
},
});
}
return false; // Modal never closes unless AJAX is successful.
});
},
此方法也不起作用(先返回 false):
onApprove() {
that.$validator.validate().then(result => {
if (!result) {
return false
}
$.ajax({
url: '/settings/user_management_add_user', method: 'POST', data: {
csrfmiddlewaretoken: that.csrfToken, password: that.password, user: JSON.stringify(that.users[that.activeUserRow]),
}, success() {
$('#modify_user_modal').modal('hide');
that.showToast('check icon', gettext('User created'));
that.activeUserRow = undefined;
that.initialQuery();
}, error(data) {
that.showToast('remove icon', gettext('User could not be created'));
if (data.responseText && data.responseText.length < 20) {
that.showToast('remove icon', data.responseText);
}
},
});
return false; // Modal never closes unless AJAX is successful.
});
},