Reputation: 1514
I'm using Laravel and Vue.js to create multiple users. I'm creating an array of users and filling the field needed to save them into the table. When all field are filled, I loop the array of users within vue.js and send them one by one to the server-side. The server-side validate them (is username and email unique value). If an error occurs, it send it back to client-side. On the client-side, the loop stop, then it add and errors array to the user.
this.users.user.push(response.data);
I want to show the errors this way:
<td class="form-group" v-bind:class="{ 'has-error': users[index].errors.includes('username') }">
<input v-model="user.username" type="text" class="form-control full-width">
</td>
The problem is that before the validation happen on server-side, there is no errors array into user. I could push an empty array into the user model before adding it to users, but I want to know if there is an other way to achieve this.
Is there another if statement that can replace users[index].errors.includes('username')
to check if errors exist and then will check if that errors array include username?
Upvotes: 3
Views: 2513
Reputation: 3529
Although the answer is absolutely right. One way to keep such computations separate from markup without making it a lot to take is using methods
:
v-bind:class="getMyClasses(index, 'username')" //replace username with the field name
methods: {
getMyClasses: function (index, field) {
return {
has-error: this.users && this.users[index] &&
this.users[index].errors &&
this.users[index].errors.includes(field)
}
}
}
Upvotes: 1
Reputation: 36770
You could do
v-bind:class = "{ 'has-error': users && users[index] && users[index].errors && users[index].errors.includes('username') }"
This will handle the undefined
Upvotes: 1