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 badges1 Answer
Reset to default 14You 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]"