40

I'm trying to learn vue.js. I'm adding list of elements, I want to add class="active" only to the first element in the for loop. following is my code:

<div class="carousel-inner text-center " role="listbox">
    <div class="item" v-for="sliderContent in sliderContents">
        <h1>{{ sliderContent.title }}</h1>
        <p v-html="sliderContent.paragraph"></p>
    </div>
</div>

So the first element should look like something this:

<div class="item active">
    <h1>WELCOME TO CANVAS</h1>
    <p>Create just what you need for your Perfect Website. Choose from a wide<br>range of Elements & simple put them on your own Canvas</p>
</div>

I'm able to get the data so everything is working perfectly fine.

And following is my script code:

<script>
export default{
    data() {
        return {
            sliderContents: [
                {
                    title: "WELCOME TO CANVAS",
                    paragraph: "Create just what you need for your Perfect Website. Choose from a wide<br>range of Elements & simple put them on your own Canvas"
                },
                {
                    title: "WELCOME TO CANVAS",
                    paragraph: "Create just what you need for your Perfect Website. Choose from a wide<br>range of Elements & simple put them on your own Canvas"
                },
                {
                    title: "WELCOME TO CANVAS",
                    paragraph: "Create just what you need for your Perfect Website. Choose from a wide<br>range of Elements & simple put them on your own Canvas"
                },
                {
                    title: "WELCOME TO CANVAS",
                    paragraph: "Create just what you need for your Perfect Website. Choose from a wide<br>range of Elements & simple put them on your own Canvas"
                }
            ]
        }
    }
}

Help me out.

2
  • 1
    v-for="(index, sliderContent) in sliderContents", then use an if statement to add the class on index 0 or 1. TBH i dont know vue but this is what you go in Angular. Commented Feb 27, 2017 at 14:08
  • @Millard in Vue3 the index is after the content: vuejs.org/guide/essentials/list.html <li v-for="(item, index) in items"> {{ parentMessage }} - {{ index }} - {{ item.message }} </li> Commented Sep 19, 2022 at 15:51

3 Answers 3

61

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 }"
Sign up to request clarification or add additional context in comments.

3 Comments

What happens if the index is a string instead of a number? How can I achieve the same result?
@Glen: I assume you're iterating over an object as opposed to an array if your index is a string. When iterating over an object with v-for the index argument is in the third position (v-for="(value, key, index) in object". You can use that argument in the expression bound to the class attribute testing if the item is the first one. But do note: when iterating over an object, the order is based on the key enumeration order of Object.keys(), which is not guaranteed to be consistent across JavaScript engine implementations.
@Glen: Alternatively you can do an assertion against the key, as opposed to the index. The directive would look like: v-for="(value, key) in object". And the class binding: :class="{ 'active': key === 'YOUR_STRING' }".
16

The easiest solution is to check every element if index is equal to 0 and then setting the active class (or the class you needed). Here is the code of class definition:

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

Here is working example of making Bootstrap Tabs:

<ul class="nav nav-tabs tab-nav-right" role="tablist">
    <li role="presentation" :class="{ 'active': index === 0 }" v-for="(value, index) in some_array" v-bind:key="index">
        {{some_array[index]}}
    </li>
</ul>

Also, if you have multiple classes you can mix them like this:

:class="['tab-pane fade', (index === 0 ? 'active in' : 'something_else')]"

Comments

1

To put active class to first element in loop, basically, you are trying to programattically control the class via VuejS.

VueJS allows you to bind the class of the anchor tag (say, but it could even be an li tag) directly to the index of the li element so that when the vuejs variable bound to the index changes, the class also changes. Check these two links for more details

This is the crux of the solution

:class="{current:i == current}

available on the fiddle below and another post that explains in blog format how class of an li element can be dynamically controlled in vuejs

https://jsfiddle.net/Herteby/kpkcfcdw/

https://stackoverblow.wordpress.com/2021/04/03/how-modern-javascript-makes-click-simulation/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.