1

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.

1 Answer 1

3

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)

Sign up to request clarification or add additional context in comments.

5 Comments

just for future information your index should not be the :key - it could give you some problems in later coding :)
what kind of problem with :key, i can get
index is always generated new after deleting something - so best case is to set a unique key.. but I think if you don't want to delete something afterwards it should be fine!
Okay ! i get it now., i will pass item unique id. thank you
@HappyVoyaging you can google this but this is a good starting point: michaelnthiessen.com/understanding-the-key-attribute

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.