In Vue.js, you can use the v-for directive to render each item in the list and combine it with v-bind:class to dynamically bind CSS classes. If you want to add class="active" only to the first element in the loop, you can achieve this by checking the index value.
Here is a specific example:
Assume you have a Vue component with an item list items, and you want to add the active class only to the first element when rendering this list:
html<template> <div> <ul> <li v-for="(item, index) in items" :key="item.id" :class="{ active: index === 0 }"> {{ item.name }} </li> </ul> </div> </template> <script> export default { data() { return { items: [ { id: 1, name: 'Item 1' }, { id: 2, name: 'Item 2' }, { id: 3, name: 'Item 3' } ] } } } </script> <style> .active { color: red; } </style>
In this example, we use Vue's v-for directive to iterate over the items array. Each <li> element is assigned a unique key (item.id) and a dynamic class attribute. Here, :class="{ active: index === 0 }" is an object syntax that applies the active class only when index equals 0 (i.e., the first element in the list).
This approach is concise and clear, effectively controlling which elements should receive specific classes while maintaining the readability and maintainability of the template.