2

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?

2
  • How do you create your multiple <tr>s? The answer depends on that. Your current code only has one <tr> Commented Jun 2, 2019 at 6:28
  • There is no for-loop here so I don't understand where are you getting the index from Commented Jun 2, 2019 at 6:30

2 Answers 2

3

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"
Sign up to request clarification or add additional context in comments.

Comments

1

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>

1 Comment

I am not able to do this due to some restraints of the project I am working on. the css needs to be per vue component - that''s why im trying to programmatically create it .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.