aCarella
aCarella

Reputation: 2578

Uing Vue.JS v-bind:class with conditional statement of dynamically created array

I have a table that is created when an array called shelves is created in my Vue app.

<table>
  <tr v-for="(shelf, index) in shelves">
    <td>
      <input type="number" v-model="shelf.maxWeight">
     </td>
  </tr>
<table>

I want to bind an html class called error to each input box created, based on the length of the value in the input box. I was thinking it would be something like this:

    <td>
      <input type="number" v-model="shelf.maxWeight" v-bind:class="error: shelf.maxWeight.length < 1">
    </td>

But whenever I try to do this, the page does not load and I get an error in the console saying:

invalid expression: Unexpected token : in
error: shelf.maxWeight.length < 1
Raw expression: v-bind:class="error: shelf.maxWeight.length < 1"

I've been looking here but can't seem to find any reference on how to specifically do this.

How do I change the class in my input field based on the length of a value in the array that my table is referencing?

Upvotes: 1

Views: 839

Answers (2)

rh16
rh16

Reputation: 1073

v-bind:class takes an object as a parameter, as described in the link you provided.

Your code should read

    <td>
      <input type="number" v-model="shelf.maxWeight" v-bind:class="{error: shelf.maxWeight.length < 1}">
    </td>

Note the curly braces surrounding the class object

Upvotes: 3

Decade Moon
Decade Moon

Reputation: 34306

You need to bind an object to class:

v-bind:class="{ error: shelf.maxWeight.length < 1 }"
              ^                                   ^

Upvotes: 1

Related Questions