[Vuejs]-How to custom v-for using v-if for make a class in div tag

0👍

You can make a function isActive that determines if the index is at 0 and than

v-bind:class="{'active': isActive}"

0👍

I found the problem.. I Think you are using a key, for an array… the key is used for a dictionary.
Here is how it works:

CSS

.active {
  background-color: #00ff00;
}

HTML:

<div id="output">
 <div class="item" v-for="(item, index) in slideItem" :key="item._id">
   <div class="carousel-caption"  :class="{active: index==1}">
     <h3>{{ item.title }} {{index}}</h3>
     <p>{{ item.body }}</p>
   </div>
 </div>
</div>

Notice that I removed the key!

JS:

var vm = new Vue({
 el: "#output",
 data: function () {
   return {
     slideItem : [
     {  '_id' :0, 'title':'title0' ,'body':'body 0'},
     {  '_id' :1, 'title':'title1' ,'body':'body 1'},
     {  '_id' :2, 'title':'title2' ,'body':'body 2'},
     {  '_id' :3, 'title':'title3' ,'body':'body 3'},
     {  '_id' :4, 'title':'title4' ,'body':'body 4'},
     {  '_id' :5, 'title':'title5' ,'body':'body 5'}
     ]
     }
   }
  });

What …
Here is the fiddle

0👍

You could do something like:

<div class="item" v-for="(item, k) in slideItem" :key="item._id"
     :class="{active: Object.keys(slideItem)[0] == k}">
    <img alt="900x500" src="http://lorempixel.com/960/720/">
    <div class="carousel-caption">
        <h3>{{ item.title }}</h3>
        <p>{{ item.body }}</p>
    </div>
</div>

Object.keys(slideItem)[0] == k gets the first key of the object and then checks that the key for current iteration matches.

👤Rwd

Leave a comment