我尝试使用vuejs创建最终使用axios进行POST请求的表单。但是,提交按钮在表单验证期间不会禁用。我试图阻止用户多次提交...
要复制的代码:
<div>
<form @submit.prevent="checkForm">
<input
type="submit"
:disabled="submitting"
:value="value"
>
</div>
位置:
checkForm( e ) {
this.submitting = true;
this.value = 'Submitting';
// Form Validation
this.submitting = false;
this.value = 'Submit';
}
答案 0 :(得分:2)
从注释中听起来,您好像在发出异步请求(在axios.post()
中,并立即设置this.submitting
和this.value
而不等待网络请求的结果,类似于这个例子:
checkForm( e ) {
this.submitting = true;
this.value = 'Submitting';
axios.post('https://foo');
this.submitting = false;
this.value = 'Submit';
}
由于axios.post()
是异步的(即返回Promise
),因此,在POST
请求发生之前就执行了以下几行。您可以将这些设置移至axios.post()
的{{3}}回调中:
checkForm( e ) {
this.submitting = true;
this.value = 'Submitting';
axios.post('https://foo').then(() => {
this.submitting = false;
this.value = 'Submit';
});
}
或者您可以像这样使用then
:
async checkForm( e ) {
this.submitting = true;
this.value = 'Submitting';
await axios.post('https://foo');
this.submitting = false;
this.value = 'Submit';
}