Search code examples
vue.jshtml-table

HTML table initialized with Vue.js : how to alternate row color


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>

Solution

  • Add an index to the v-for

    <template v-for="(entry, index) in filteredHeroes">
        <tr :class="{'table-light': index % 2}">