How to put class=”active” to first element in vuejs for loop

const TextComponent = {
  template: `
    <p>{{ text }}</p>
  `,
  
  props: ['text'],
};

new Vue({
  components: {
    TextComponent,
  },
  
  template: `
    <div>
      <text-component
        v-for="(item, index) in items"
        :class="{ 'active': index === 0 }"
        :text="item.text">
      </text-component>
    </div>
  `,
  
  data: {
    items: [
      { text: 'Foo' },
      { text: 'Bar' },
      { text: 'Baz' },
    ],
  },
}).$mount('#app');
.active {
  background-color: red;
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title></title>
</head>
<body>
  <div id="app"></div>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script>
</body>
</html>

Above is a snippet demonstrating a solution to your problem. Here’s an outline of it:

Inside v-for blocks we have full access to parent scope properties. v-for also supports an optional second argument for the index of the current item.

– https://v2.vuejs.org/v2/guide/list.html#Basic-Usage

The v-for directive has a second argument giving you the index of the item.

v-for="(item, index) in items"

Since you want the active class on the first item you can use an expression testing if the index is 0 and bind it to the class attribute.

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)