【问题标题】:How to properly add conditional class to Alpine JS x-for template?如何正确地将条件类添加到 Alpine JS x-for 模板?
【发布时间】:2021-05-30 08:22:46
【问题描述】:

我正在尝试遍历一个循环并为 4 项以上的每个元素添加一个条件类,以便使用 tailwindcss 进行一些响应式样式。

以前我在其他类中添加了循环,效果很好:

<template x-for="(card, index ) in cards" :key="index">
    <div class="w-40 h-64"
         x-modal="card"
         :class="card.someOtherClass"
    >
        <div class="card-content" :id="'card-' + card.id">
        </div>
    </div>
</template>

但是我需要添加一个条件语句来检查项目数是否超过 4。 我查看了以下先前提出的问题:

AlpineJS: How can I add a class to an element conditionally?

这建议使用{ 'class-name': statement },所以我做了以下操作:

<template x-for="(card, index ) in cards" :key="index">
    <div class="w-40 h-64"
         x-modal="card"
         :class="[card.someOtherClass,
             {'bg-green-500':  index > 3 },
          ]"
        >
        <div class="card-content" :id="'card-' + card.id">
        </div>
    </div>
</template>

但我将这个&lt;div class="w-40 h-64 some-other-class [object Object]"&gt; 传递给浏览器中的相关HTML。如何从该对象中获取相关值?

【问题讨论】:

    标签: javascript laravel alpine.js


    【解决方案1】:

    改变风格的例子:

    <div x-data="{ show: false }">
          <button @click="show = !show" :class="{ 'active': show }">
        Toggle Button
        </button>
        
    </div>
    

    css:

    .active {
      background-color: red;
    }
    

    https://codepen.io/bubnenkoff/pen/RwLoBXd

    【讨论】:

      【解决方案2】:

      要使card.someOtherClass 成为变量属性名称,请将其括在方括号中。然后,将其设置为 true,以便始终将其添加到类列表中。

      :class="{[card.someOtherClass]: true, 'bg-green-500': index > 3 }"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-01-02
        • 2015-09-24
        • 1970-01-01
        • 2018-01-19
        • 1970-01-01
        • 2011-08-15
        • 2020-09-20
        • 1970-01-01
        相关资源
        最近更新 更多