如何在for循环中的x-bind alpine.js中添加条件?

How to add a condition in x-bind alpine.js in foor loop?

我想在 alpine.js

中的 for 循环的偶数和奇数索引上进行一些 class 绑定
<template x-for="(item, index) in myForData" :key="index">
      <div class="bg-primary-500 text-white border-gray-900 rounded-lg block w-64 h-24 text-lg shadow hover:shadow-lg hover:rounded transition duration-150 ease-in-out transform hover:scale-105 p-3" 
      :class="{ 'bg-green-500':  index % 2 == 0 }"
        </div>
</template>

我尝试使用模数。也许你们中有些人有更好的主意?

您可能想要真正切换背景值:

<template x-for="(item, index) in myForData" :key="index">
      <div class=" text-white border-gray-900 rounded-lg block w-64 h-24 text-lg shadow hover:shadow-lg hover:rounded transition duration-150 ease-in-out transform hover:scale-105 p-3" 
      :class="{ 'bg-primary-500': index % 2 === 1, 'bg-green-500':  index % 2 == 0 }"
        </div>
</template>