Home > Mobile >  How to add css class based on conditions in v-for
How to add css class based on conditions in v-for

Time:10-28

I want to set class based on index number. for example

<div > //item no 1 in v-for loop
<div > // item no 2
<div > // item no 3
<div > // item no 4
<div > // item no 5-7

how can we achieve that.

<div  v-for="(destinations, index) in pageData.topDestinations" :key="index">
        <div >
          <div  v-bind:style="`background-image:url('${destinations.destImage}');`"></div>
          <div ></div>
          <a  href="#"></a>
          <div >
            <h5 >{{ destinations.name }}</h5>
            <p >Starts {{ destinations.priceCurrency }} {{ destinations.priceStarts }}</p>
          </div>
        </div>
      </div>

currently everytime has col-md-4 class. but i want it dynamic.

CodePudding user response:

try following set a class in your <div> where your v-for is standing like following and with that you pass your index to your methods:

:

after that go to your methods and check your index based on your numbers and return the width:

getWidth(index) {
  if(index == 1) {
    return "col-md-7";
  }
  if(index == 2) {
    return "col-md-5"
  }
  ....
  if(index >= 5 && index <= 7) {
    return "col-md-4";
  }   

Attention: index starts at 0 - your first check should be if(index == 0)

  • Related