我这里有一个vue laravel spa,它使用axios vform
来显示错误验证消息。我目前使用的是axios vform
1.0.1,我认为语法使用正确。然而,单击提交后,我在控制台中收到错误,而不是显示验证消息。
这是我的标记和vue:
<script>
import Form from 'vform'
export default {
data: () => ({
form: new Form({
name: '',
description: ''
}),
}),
methods: {
addDesignation() {
this.form
.post('/api/designations', this.form)
.then(response => (
this.$router.push({ name: 'designations' })
))
.catch(err => console.log(err))
.finally(() => this.loading = false)
}
}
}
</script>
<template>
<main>
<h3 class="text-2xl text-gray-800 font-bold leading-none mb-6">Create Designation</h3>
<div class="px-5 py-6 shadow-sm rounded-md bg-white">
<div class="row">
<div class="col-md-6">
<form @submit.prevent="addDesignation">
<div class="mb-4">
<label class="block text-gray-700 text-sm font-bold mb-2 required" for="name">Name</label>
<input class="shadow appearance-none border rounded w-2/4 py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" name="name" id="name" type="text" placeholder="Name" tabindex="1" v-model="form.name" :class="{ 'invalid': form.errors.has('name') || form.errors.has('name') }" />
</div>
<div class="mb-4">
<label class="block text-gray-700 text-sm font-bold mb-2 required" for="description">Description</label>
<textarea rows="4" class="shadow appearance-none border rounded w-2/4 py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" name="description" id="description" placeholder="Description" tabindex="2" v-model="form.description" :class="{ 'invalid': form.errors.has('description') || form.errors.has('description') }"></textarea>
</div>
<button type="submit" class="sm:hidden md:flex bg-blue-500 hover:bg-blue-400 text-white font-bold py-2 px-4 border-b-4 border-blue-700 hover:border-blue-500 rounded outline-none focus:outline-none">Create</button>
</form>
<vue-progress-bar></vue-progress-bar>
</div>
</div>
</div>
</main>
</template>
然后这是控制台中的错误消息:
VM559:1 POST http://localhost:8000/api/designations 422 (Unprocessable Content)
网络显示:
message: "The given data was invalid.", errors: {description: ["The description field is required."]}}
errors: {description: ["The description field is required."]}
message: "The given data was invalid."
您应该捕获这样的错误:
.catch(error => {
this.errors = error.response.data.errors;
// console.log(this.errors);
})
以及
data(){
errors: {}
}
网络中的错误是由拉拉威尔发送的。它不在那里,因为你记录了这个
.catch(err => console.log(err))
显示以下文本区域的描述错误:
<span
v-if="errors['description']"
role="alert"
>{{ errors["description"]}}
</span>