Method 1: Utilize loop index
To only bold the first element in a loop, you can simply use the loop index to apply the bold class to the first item.
See it in action -
new Vue({
el: "#app",
data() {
return {
first: [
{
id: 1,
name: "Hello"
},
{
id: 2,
name: "Bye"
},
{
id: 3,
name: "Nice to meet you"
}
]
}
}
})
.cat_name
{
font-weight: bold;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div v-for="(item,index) in first" :key="item.id" class="list">
<p :class="{'cat_name': index == 0}" >{{item.name}}</p>
</div>
</div>
Method 2: Leverage the :first-child rule
The CSS :first-child
rule can also be used, however, remember that "The :first-child
CSS pseudo-class represents the first element among a group of sibling elements." This means all p
elements should follow this structure-
<p>Hello</p>
<p>Bye</p>
<p>Nice to meet you.</p>
If your loop-generated HTML looks like this-
<div>
<p>Hello</p>
</div>
<div>
<p>Bye</p>
</div>
<div>
<p>Nice to meet you</p>
</div>
Where each p
element is wrapped within an individual div
, they are no longer siblings to each other. As a result, the :first-child
CSS rule will apply to all p
elements since every p
element is the first child of its parent div
element.
If you still prefer this method, then directly target the p
elements in your loop.
See it in action -
new Vue({
el: "#app",
data() {
return {
first: [
{
id: 1,
name: "Hello"
},
{
id: 2,
name: "Bye"
},
{
id: 3,
name: "Nice to meet you"
}
]
}
}
})
.list p:first-child {
font-weight: bold;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div class="list">
<div>
<p v-for="(item,index) in first" :key="item.id">{{item.name}}</p>
</div>
</div>
</div>
Note-
If looping directly on p
elements is not feasible, it is recommended to utilize Method 1.