【发布时间】:2018-06-22 15:58:00
【问题描述】:
我很难弄清楚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.
});
},
【问题讨论】:
-
您从不等待ajax请求的结果,因此在ajax调用后直接执行返回false。
-
如果 return false 被执行,那么模式不应该关闭(因为 OnApproval 是 false),所以这并不能解释为什么它总是关闭(也就是返回 true)。
-
您的 onApprove 方法在此 sn-p 中返回未定义:您没有在函数内部返回任何内容
-
你是如何使用你的 onApprove 方法来关闭你的模态的?
-
如果你想关闭模态,看起来你必须手动完成:github.com/Semantic-Org/Semantic-UI/issues/935 它不适用于异步验证
标签: javascript vue.js vee-validate