Conditionally Apply CSS Classes to Elements with v-bind in Vue

Share this video with your friends

Send Tweet
Published 3 years ago
Updated a year ago

We'll see how we can add CSS classes conditionally to our HTML elements using the object syntax. We'll explore how different classes can be added atomically and that these can be built on top of a defined base class.

In this case, we'll check if our soldOut computed property is returning true and if it is we'll gray out the event image.

Instructor: [0:00] A common need for binding is to update the classes on an element. Since it's an attribute, we could use v-bind to be able to update this particular class. If we're combining multiple classes, working with string concatenation is frustrating sometimes. Vue provides some added functionality for this purpose.

[0:22] Let's look at this image that's being represented here. Let's change this image if the tickets have been sold out. We use :class as normal. Inside our quotes, we're going to parse an object. The key of that object is the CSS class that we will apply if the value is truthy. In this case, I'm going to pass the value, sold out.

[0:43] To remind myself what sold out is, I can say that sold out is true when tickets equal zero. Let's see what happens when I buy all 10 tickets. That class has been applied, which is knocking back the opacity of the image. If we inspect the element, we can see the sold out class has been added.

[1:03] We can have base classes. Say we had a class called base class and did the same thing. We need to buy all 10 tickets. We still have that base class, but Vue has handled adding the sold out class. We can parse more than one class with its corresponding truthy statement. Let's hide this image if hidden is true. Let's add prop of hidden, and let's add a CSS class of hidden.

[1:36] Now, we've got our base class, our Vue tools. Let's change hidden to true, and the image is gone. Let's purchase our 10 tickets. If we bring back our image, we can see our sold out class has been applied. We can add our hidden back as well. We can see that sold out, hidden, and base class have all been applied based on the logic that we've parsed through in that object.