SoFunction
Updated on 2025-02-28

Vuejs in v-for, use index to add class to the first item

(1) In v-for, use index to add class to the first item

View code fragments on CODE derived to my code fragment

<a class="list-group-item" :class="{'active':!index}" v-for="(i,index) in announcement"> 

index comes from v-for, i represents the element of the traversed array, and index represents the index.

Since index starts from 0, if you want to specify that the first item has the active class, then use v-bind:class="{'active':!index}"

The first item was originally false(0), the second item and followed by true(>0), and the value is reversed by logical non-operators.

Therefore, the first item has the active class, but the latter one does not.

If there is a certain class other than the first item, it can also be achieved by not adding logical non-operators.

Similarly, you can use an expression like index==2 to get this class in the third item.

Notice,My version is Vuejs2.0, so it seems that $index cannot be replaced.

In the above article Vuejs, in v-for, the first method of adding class using index is the entire content that the editor has shared with you. I hope you can give you a reference and I hope you can support me more.