I want to show this div only if errors: []
have value
<div v-show="errors.length" >
<span v-for="(error, key) in errors" :key="key">
<li v-for="(errorItem, errorKey) in error" :key="errorKey" >{{errorItem}}</li>
</span>
</div>
I have create a validation for my form and polpulate errors: []
array from request i get from backend. But i want to show this div only if i have errors. How can i do this?
methods:{
//if i request will catch error do this
.catch(error => {
this.errors = error.response.data.errors
}
if errors have value will look like this
errors:Object
email:Array[1]
name:Array[1]
CodePudding user response:
You may use Object.keys(errors).length
instead of errors.length
, since errors
is an object.
// pervious
<div v-show="errors.length" >
// new
<div v-if="hasErrors" >
computed: {
hasErrors() {
return Object.keys(this.errors).length > 0;
}
}
update:
to enable Toastify()
you may add the Object.keys(errors).length
in catch
methods: {
.catch(error => {
this.errors = error.response.data.errors;
if(Object.keys(error.response.data.errors).length > 0) {
Toastify({text: error.response.data.message,...})
}
}
(But I guess you are using requests-sender something like axios
, you can add your Toastify()
in the axios global interceptor)
update:
For Laravel backend, I recommend you use vform for form validations and alerts.
But if you want to handle this manually, there is a basic login form example:
your Laravel validator may look like below
return [
'email' => 'required|email',
'password' => 'required|string|min:8|max:32'
];
your login form via Vue2 Single-File-Component
<template>
<form
@submit.prevent="login">
<input
name="email"
type="email"
v-model="form.email"
described-by="email-alert"/>
<p
v-if="errors.email.length"
id="email-alert">
<span
v-for="error in errors.email"
v-text="error"/>
</p>
<!-- You may combine the `<input/>` and `<p/>` as a Vue-Component -->
<input
name="password"
type="password"
v-model="form.password"
described-by="password-alert"/>
<p
v-if="errors.password.length"
id="password-alert">
<span
v-for="error in errors.password"
v-text="error"/>
</p>
<button>
login
</button>
</form>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
form: {
name: '',
password: '',
},
errors: {
name: [],
password: [],
}
}
},
methods: {
login() {
axios.post('/authorizations', this.form)
.then(() => {
// no errors
})
.catch(error => {
this.errors = error.response.data.errors
});
}
}
}
</script>