Add class based on condition (for last rendered element with v-for)

Incredible picture Incredible · Oct 2, 2017 · Viewed 8.6k times · Source

I'm making a table in Vue.js and rendering some of the columns with the v-for directive:

<td v-for="(item, index) in items"> {{ item.name }} </td>

There is an unknown element count and I have to add a class to the last rendered element. I cannot use :last-child or :last-of-type because it is not the last <td> element in a row, it is just the last rendered element with v-for but there are also following <td> elements.

How could we achieve this in Vue.js?

Answer

Mihai Alexandru-Ionut picture Mihai Alexandru-Ionut · Oct 2, 2017

You have to use v-bind:class directive.

<td v-for="(item, index) in items"
    v-bind:class="{ active: index==items.length-1 }"> {{ item.name }} </td>

CSS class:

.active {
   //some style
}

The solution is checking if index of an element is equal to items.length-1

v-bind:class="{ active: index==items.length-1 }"

Working example:

new Vue({
  el: '#app',
  data: {
    items:[{"name":"A"},{"name":"B"},{"name":"C"}]
  }
})
.active {
  color: red;
}
<script src="https://unpkg.com/vue"></script>

<div id="app">
  <table>
    <tr>
      <td v-for="(item, index) in items"
          v-bind:class="{ active: index==items.length-1 }"> {{ item.name }} </td>
    </tr>
  </table>
</div>