Conditionally Apply an Array of CSS Classes to Elements 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 array syntax. We'll explore how different classes can be added atomically and that these can be build on top of a defined base class.

You'll see that we can pass in terneries that will conditionally apply a class or use the object syntax to conditionally apply a class.

Instructor: [0:00] Vue provides another syntax to be able to add classes to an element. Instead of parsing an object, we could parse an array. This array will take some props. In this case, soldOut class and hidden class. We need to parse those props, so, sold out class. If you remember, that was soldOut, and hidden class was hidden.

[0:30] We can see that those two classes have been parsed straight to our element, soldOut and hidden. If you want to parse those dynamically, we could use a ternary operation. We could say, sold out, then soldOut class, otherwise string, and equally, hidden, hidden otherwise string. Now we can parse on and check that soldOut is being applied to our image once we're sold out. Check again that if we set hidden to true, then that will disappear.

[1:18] That can get quite verbose and messy. We can parse down an array of objects. Instead, we could do what we've done previously. We can have soldOut when soldOut, and hidden when hidden. Again, buying all the tickets, soldOut gets applied, setting hidden to true, hidden gets applied.