emk
emk

Reputation: 185

Bind multiple classes to a single variable

While using Tailwind with utility-first approach to css, I often find the need to bind multiple classes to a single variable.

For instance, to style an input form, I need to add border-red, color-red, etc if there is an error.

Is there a nice and elegant way to express this in Vue instead of writing v-bind:class="{ 'border-red': error, 'text-red': error }?

Upvotes: 3

Views: 1310

Answers (2)

EscapeNetscape
EscapeNetscape

Reputation: 2939

Another easy solution:

:class="error && 'border-red text-red'"

or for if, else

:class="error ? 'border-red text-red' : 'border-green'"

You also can concatenate strings to classnames:

:class="'border-'+borderColor"

Upvotes: 2

Decade Moon
Decade Moon

Reputation: 34286

You can combine both classes into the same property:

:class="{ 'border-red text-red': error }"

Upvotes: 7

Related Questions