Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialSondra Coffin
6,909 Points[Vue.js] Syntax for adding multiple class bindings?
When the instructor initially shows us how to use v-bind:class, she passes an object containing two classes (less and more) and their associated expressions as the value:
v-bind:class="{less: media.showDetail, more: !media.showDetail}"
Later (around 4:00), she says you can pass another class in by making the value of the class binding an array, with the object we passed previously as one item, and the new class binding as a separate item:
v-bind:class="[{less: media.showDetail, more: !media.showDetail}, media.type]"
My question is, how is this syntax determined? What determines which styles needs to be in objects? What determines when to put styles in an array? What determines which styles can be together in an object and which can't? I played around with the syntax locally but wasn't able to discern a definite "rule" for any of these questions.
Thanks in advance!
1 Answer
Elisa Burghard
9,276 PointsIf you want to only add one class, you don't need the array. As soon as you want to add more classes, you need the [] and separate the different classes by comma.
In this part: {less: media.showDetail, more: !media.showDetail}
, it will be determined which class (less or more) will be applied to the same "thing" (the list item). This depends on if details of the media are shown (arrow up) or not (arrow down). They are two different classes, but only one will be applied, this is why they are in {} together.
When you look at the ternary syntax, it becomes more clear:
[media.showDetail ? 'less' : 'more', media.type]
media.showDetail ? 'less' : 'more'
decides which of the two classes will be applied
media.type
will be applied, no matter what and needs to be separated from the other class (less or more)
The results could be:
-
v-bind:class="['less', media.type]"
v-bind:class="['more', media.type]"
Hope this helps! Happy coding