softcode
softcode

Reputation: 4648

Class Binding ternary operator

I have some rather cumbersome logic I would like to apply to an element class.

:class="{sportTypes.sports.indexOf(sport) > -1 ? 'is-primary' : 'is-outlined'}"

The above doesn't work, while the following does:

:class="{'is-outlined': sportTypes.sports.indexOf(sport) > -1}"

I get the following error

template syntax error - invalid expression:

Any ideas what's wrong with the first part?

Upvotes: 34

Views: 57246

Answers (3)

Saurabh
Saurabh

Reputation: 73609

As par the syntax given in the docs here, you can use following array syntax to achieve this:

:class="[sportTypes.sports.indexOf(sport) > -1 ? 'is-primary' : 'is-outlined']"

Upvotes: 6

m_callens
m_callens

Reputation: 6360

When you're applying class bindings in Vue, you only use braces for object style assignments like in your second statement. For single bindings you just do...

:class="sportTypes.sports.indexOf(sport) > -1 ? 'is-primary' : 'is-outlined'"

and if you wanted to apply multiple bindings in the same logical statement, you surround them in [] instead of {} and separate by commas.

Upvotes: 5

Phil
Phil

Reputation: 164776

You have unnecessary braces. The latter expression is an object whereas the first is simply a ternary expression that returns a string.

:class="sportTypes.sports.indexOf(sport) > -1 ? 'is-primary' : 'is-outlined'"

Upvotes: 69

Related Questions