简体   繁体   中英

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?

You could do

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

This will handle the undefined

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)
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM