Conditionally Apply an Array of CSS Classes to Elements in Vue

Share this video with your friends

Social Share Links

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.

egghead
egghead
~ 8 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today