Home » vue » How to add css class based on conditions in v-for

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

Posted by: admin November 26, 2021 Leave a comment

Questions:

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

<div class="col-md-7"> //item no 1 in v-for loop
<div class="col-md-5"> // item no 2
<div class="col-md-4"> // item no 3
<div class="col-md-8"> // item no 4
<div class="col-md-4"> // item no 5-7

how can we achieve that.

<div
  class="col-md-4
  "v-for="(destinations, index) in pageData.topDestinations" 
  :key="index"
>
  <div
    class="banner _h-45vh _br-4 _bsh-xl _bsh-light banner-animate banner-animate-mask-in banner-animate-zoom-in banner-animate-slow"
  >
    <div 
      class="banner-bg"
      v-bind:style="`background-image:url('${destinations.destImage}');`"
    ></div>
    <div class="banner-mask"></div>
    <a class="banner-link" href="#"></a>
    <div
      class="banner-caption _bg-w _p-20 _w-a banner-caption-bottom banner-caption-dark"
    >
      <h5 class="banner-title">{{ destinations.name }}</h5>
      <p class="banner-subtitle _mt-5 _fw-n">
        Starts {{ destinations.priceCurrency }} {{ destinations.priceStarts }}
      </p>
    </div>
  </div>
</div>

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

Answers:

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:

:class="getWidth(index)"

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)