Sometimes, we want to put class=”active” to first element in a Vue.js for loop.
In this article, we’ll look at how to put class=”active” to first element in a Vue.js for loop.
How to put class=”active” to first element in a Vue.js for loop?
To put class=”active” to first element in a Vue.js for loop, we can pass a dynamic value to the class
prop.
For instance, we write
<template>
<div>
<text-component
v-for="(item, index) in items"
:class="{ active: index === 0 }"
:text="item.text"
>
</text-component>
</div>
</template>
<script>
//...
export default {
//...
components: {
TextComponent,
},
data() {
return {
items: [{ text: "Foo" }, { text: "Bar" }, { text: "Baz" }],
};
},
//...
};
</script>
to set :class
to { active: index === 0 }
to only set the class
attribute to active
if index
is 0.
We get the index
of the item being looped through from the 2nd parameter returned by v-for
.
Conclusion
To put class=”active” to first element in a Vue.js for loop, we can pass a dynamic value to the class
prop.