Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js : v-bind:class if an array exist and that array include something

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?

like image 349
Elie Morin Avatar asked May 28 '26 00:05

Elie Morin


1 Answers

You could do

v-bind:class = "{ 'has-error': users && users[index] && users[index].errors && users[index].errors.includes('username') }"

This will handle the undefined

like image 98
Julian Avatar answered May 30 '26 15:05

Julian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!