最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Multiple class bindings in AlpineJS? - Stack Overflow

programmeradmin3浏览0评论

I'm trying to attach two :class bindings to a single element within an x-for loop. Usually this could be achieved by passing in a single object with multiple key:value pairs. In this instance however, one is a condition, the other is a property of the loop:

Condition:

:class="{'active': colours.includes(arrayItem.class)}"

Property:

:class="arrayItem.class"

Both of which work separately. I've tried adding them as separate attributes but only the first gets applied. I've also tried this (to no avail):

:class="{'active': colours.includes(arrayItem.class), arrayItem.class}"

I've searched through the docs but haven't found a solution.

Example: /

I'm trying to attach two :class bindings to a single element within an x-for loop. Usually this could be achieved by passing in a single object with multiple key:value pairs. In this instance however, one is a condition, the other is a property of the loop:

Condition:

:class="{'active': colours.includes(arrayItem.class)}"

Property:

:class="arrayItem.class"

Both of which work separately. I've tried adding them as separate attributes but only the first gets applied. I've also tried this (to no avail):

:class="{'active': colours.includes(arrayItem.class), arrayItem.class}"

I've searched through the docs but haven't found a solution.

Example: https://jsfiddle/owjbu1ay/10/

Share Improve this question asked Nov 25, 2020 at 21:10 AlluziionAlluziion 1811 silver badge10 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 14

You can use the array of classes when binding to the class attribute. The issue here is the object syntax {} here. You can use array of classes and use the ternary operator to conditionally render classes as shown below.

Now if the colours array includes the arrayItem.class it will apply the active class,

and the arrayItem.class will be the 2nd class applied without any conditions.


:class="[colours.includes(arrayItem.class) ? 'active' : '' , arrayItem.class]"

发布评论

评论列表(0)

  1. 暂无评论