0

I'm a beginner in Vue.js. I have a Vue.js script that stores some data in order to put it in a table. I can manage put it in the table, but I can't figure out how to alternate the color in the rows of the table (I just have to put a 'class="table-light"' in the ).

I tried doing something like "var i = 0;" and then I wanted to do something like : if(i % 2 == 0) { print ''; } else { ... } But that doesn't work so far because I don't think there's any function to print something, and I can't even get my variable to increment. If anyone could help me figure this out...

//Where I store the data
var demo = new Vue({
    el: '#demo',
    data: {
        searchQuery: '',
        gridColumns: ['nom', 'description', 'url'],
        gridData: [
            { nom: 'test', description: 'test', url: 'test' },
            { nom: 'test', description: 'test', url: 'test' },
            { nom: 'test', description: 'test', url: 'test' }
        ]
    }
})






<script type="text/x-template" id="grid-template">

    var i = 0;

    <table class="table table-hover">
        <thead>
            <tr class="table-title">
                <th v-for="key in columns"
                    @click="sortBy(key)"
                    :class="{ active: sortKey == key }">
                    {{ key | capitalize }}
                    <span class="arrow" :class="sortOrders[key] > 0 ? 'asc' : 'dsc'">
                    </span>
                </th>
            </tr>
        </thead>

        <tbody>

            <template v-for="entry in filteredHeroes">
 //-----------------------------------------------------------------
            //Where I'm supposed to add class="table-light"

                <tr>
//-----------------------------------------------------------------

                    <th scope="row"> {{entry['nom']}} </th>
                        <td> {{entry['description']}} </td>
                        <td>{{entry['url']}} <a v-bind:href="entry['url']" class="ni ni-curved-next pull-right"></a></td>
                </tr>
            </template>
        </tbody>
    </table>
</script>
1

2 Answers 2

3

Add an index to the v-for

<template v-for="(entry, index) in filteredHeroes">
    <tr :class="{'table-light': index % 2}">
Sign up to request clarification or add additional context in comments.

2 Comments

Hey, thank you so much : it works ! But can you tell me where "index" comes from ? :)
it it the index in the filterdHeroes array, and you can indicate it in the second component as shown in the v-for phrase.
1

this works for me:


.table tbody tr:nth-child(odd) {
    background-color: #f2f2f2;
}

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

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.