It’s sort of cool to add a class to a component.
But the real fun begins when you can conditionally bind classes — turning them on and off as you wish.
In this article we’ll cover:
- A refresher on how variable binding works in Vue
- Using guard expressions to conditionally add a class
- How ternaries can be used to bind classes conditonally
- Doing all of this with many classes at once!
To refresh your memory, to bind a variable to a prop, class, or style, we use this syntax:
If the value of
blue-text, it will add the class
.blue-text to the
Normally we shorten the binding syntax by removing
v-bind, and we’re left with just this:
But this will always apply the value of
className as a class to our
How can we toggle this behaviour and make it conditional?
There is a cool trick using the logical
&& (AND) that allows us to conditionally apply a class:
This is known as a guard expression.
true, it will set the class to whatever the value of
But how does it work?
Here we have the variable
useTheme which is a boolean, and
theme is the value of the theme class.
&& (AND) operator will short-circuit if the first value is
Since both values need to be
true in order for the expression to be
true, if the first is
false there is no point in checking what the second one is, since we already know the expression evaluates to
false, the expression evaluates to
false and no dynamic class name is applied.
useTheme is true, it will also evaluate
theme, and the expression will evaluate to the value of
theme. This will then apply the value of
theme as a classname.
We can do a similar trick with ternaries.
If you aren’t familiar, a ternary is basically a short-hand for an if-else statement.
They look like this:
Sometimes though, we’ll format them like this for readability:
expression evaluates to
true, we get
ifTrue. Otherwise we will get
Their main benefit is that they are concise, and count as only a single statement. This lets us use them inside of our templates.
Ternaries are useful if we want to decide between two different values inside of the template:
true, we apply
dark-theme as our class name. Otherwise we choose
Sometimes the logic needed to decide what class name to apply is a little more complicated.
In these cases, it doesn’t really fit that nicely inside of the template, and instead you want to put it into a computed prop:
Computed props are the real workhorse of Vue. In my opinion, most of your logic should be inside of computed props.
There are tons of other ways to apply classes conditionally in Vue.
To apply more than one class at a time, you can:
- Use the array syntax
- Use the object syntax
I cover these, as well as generating class names on the fly.