v-for中如何根据条件添加cssclass

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

我想根据索引号设置class。例如

<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

我们怎样才能做到这一点。

<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>

目前每次都有 col-md-4 class。但我希望它是动态的。

尝试在你的 <div> 中设置一个 class,你的 v-for 就像下面一样站立,然后将你的索引传递给你的方法:

:class="getWidth(index)"

之后转到您的方法并根据您的数字和 return 宽度检查您的索引:

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";
  }   

注意:索引从 0 开始 - 您的第一个检查应该是 if(index == 0)