注意!!
此解决方案基于ES6,因此您可能需要将其转换为ES5
我之前遇到过这个问题,所以我编写了一个简单的类来帮助管理来自服务器的验证消息。
https://gist.github.com/nonsocode/e6f34a685f8be1422c425e3a20a69a4b
您可以通过将此导入到模板来使用它
import ErrorBag from 'path-to-errorbag-class'
把它用在你的
data
像这样的方法
data: function() {
return {
name: '',
email: '',
password: '',
confirm_password: '',
errors: new ErrorBag,
};
},
在模板中,您可以检查是否存在验证错误,然后决定如何处理它。我假设你用的是bootsrap 4
<div class="form-group row">
<label for="email" class="col-md-4 col-form-label text-md-right">Email Address</label>
<div class="col-md-6">
<input type="email" v-model="email" required autofocus :class="{'form-control': true, 'is-invalid': errors.has('email')}">
<div class="invalid-feedback" v-if="errors.has('email')" >{{ errors.first('email') }}</div>
</div>
</div>
在ajax请求的catch方法中,
axios(...)
.then(...)
.catch(function (error) {
if (error.response && error.response.status == 422) {
const errors = err.response.data.errors;
this.errors.setErrors(errors);
}
});
成功提交到服务器后,可以调用
clearAll
方法清除包中的所有错误