3

I am using vue's v-if to dynamically show and hide table elements, and I use zebra backgrounds for these elements. The problem is when I show a row, the background colours change as there is now a different number of elements in the table. This is confusing to look at, so i would prefer if the rows that are hidden to begin with don't affect the formatting so the zebra colouring stays consistent.

Below is the css i am using to highlight every other tr element:

.content-table {
    .table-content {
        table {
            tbody {
                tr:nth-child(even) {
                    background-color: #00ff0d;
                }
            }
        }
    }
}

And a simplified example of the code i am using

<tbody>
    <template v-for="item in list">
        <tr class="zebra">
            //blah
        </tr>

        <tr v-if="item.accordion">
            //blah
        </tr>
    </template>
</tbody>

The accordion property of each item is false by default so clicking to expand will show this new row, changing the background colour of all items below it in the table.

I know of using CSS's .zebra:nth-of-type(even) selector as I have seen examples on similar questions however as far as I can tell this won't work for my code as if i selected only the first set of tr elements using a class, it will still count all tr elements in the same parent class.

Please could anyone suggest a solution to my problem or help me understand how I've missed something with :nth-of-type.

Thanks

2
  • 1
    You can follow this thread to use INDEX in v-for https://stackoverflow.com/questions/49675988/how-to-get-the-v-for-index-in-vue-js and use this index to dynamically add class if the index is even, Hope this helps a little Commented May 24, 2021 at 16:08
  • @NotTheWaquar Thanks for your post, I was able to use this to find my answer, which i posted below Commented May 24, 2021 at 17:23

1 Answer 1

1

I was able to get the formatting I wanted using vue's conditional styling.

<tbody>
    <template v-for="(item, index) in list">
        <tr :style="(index % 2 == 0) ? {'background-color': '#f7f8f9'} : {'background-color': '#f1f3f5'}">
            //blah
        </tr>

        <tr v-if="item.accordion">
            //blah
        </tr>
    </template>
</tbody>
Sign up to request clarification or add additional context in comments.

Comments

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.