Search code examples
javascriptarraysvue.jsconditional-statementstwo-way-binding

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?


Solution

  • 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