How can I style the first element of a v-for in vue?

Viewed 658

I want to set an active class just to first button in this code:

<button
  class='optional-red-outlined-btn'
  v-for="(item, index) in faq"
  :key="item._id"
  @click="btnIndex = index"
>
  {{ item.question }} 
</button>

It means than when the page is loaded, if 4 buttons were in it, first of them should have optional-red-outlined-btn class and active class but others just have optional-red-outlined-btn class.

of course but i want when click on other button remove active of first button ,I use it for just one button have active style button:focus{ background-color: $optional-red; color: #fff; } but i want in default first button have this style

3 Answers

You can make a dynamic class based on a condition like

:class="{ active: index === 0 }"

As shown in the official documentation

I am pretty sure your btnIndex variable has 0 value by default. So you can apply conditional class

:class="btnIndex == index ?'active':''"

You can do that completely without vuejs. Use simple CSS. Give the button a special class and then:

button.special {
 color: blue
}
button.special:first {
 color: red
}
Related