david
david

Reputation: 6805

How to find element of table row with css and vue.js?

I want every other row to be gray, but in the following example - all rows become gray.

  <table>    
    <tr v-for="i in item.env_vars" :style="{'background': index % 2 === 0 ? '#eee' : '#ccc' }">
      <td> test1 </td>
      <td> test2 </td>
      <td> test3 </td>
    </tr>
  </table>

and I see this error in vue admin tool:

Property or method "index" is not defined on the instance but referenced during render.

What is wrong with my code?

Upvotes: 2

Views: 324

Answers (2)

ray
ray

Reputation: 27275

I'm not familiar with vue, but I think you need to add an index variable to your loop:

<tr v-for="(i, index) in item.env_vars"

Upvotes: 3

ray
ray

Reputation: 27275

You can do this with a simple nth-child rule:

table {
  width: 100%;
}

tr:nth-child(odd) {
  background: #eee;
}

tr:nth-child(even) {
  background: #ccc;
}
<table>
  <tr>
    <td>hi</td>
  </tr>
  <tr>
    <td>hi</td>
  </tr>
  <tr>
    <td>hi</td>
  </tr>
  <tr>
    <td>hi</td>
  </tr>
</table>

Upvotes: 1

Related Questions