Reputation: 707
I have this pen: https://codepen.io/nuzze/pen/gOYjKmx
As you see, I have 2 items with 3 properties (name, id, location).
So, when you click on the favorites button, a class named "favorites" its added to the 'li' tag and when you click again (unfavorite) the "favorites" class is removed. But now, I want to add statically the 'location' propertie as a class.
Let's see an example with 'Camp Nou' item:
{
name: 'Camp Nou',
id: 'campNou',
location: '10'
}
The result I want is the next one:
<li class="10"></li>
And if is marked as favorites..
<li class="10 favorites"></li>
Hope you can help me, I have been with this problem for a long time.
Thanks
Upvotes: 3
Views: 3299
Reputation: 90068
<li :class="[{'favorites': complejosVotes[complejo.id]}, complejo.location]">
... will do.
See it working.
Do note if you want to use class names starting with numbers or special characters you need to escape them (.10
selector becomes .\31 0
, as you replace 1
with \31
- ending space required, and it doesn't have the usual meaning of spaces in CSS selectors - here it means "end of escape sequence").
It gets as weird as this:
.\30 {
color: red;
}
.\31 {
color: blue;
}
.\31 .\30 {
color: orange;
}
.\31 .\30 {
color: green;
}
<div class="0">.0</div>
<div class="1">
.1
<div class="0">.1 .0</div>
</div>
<div class="1 0">.1.0</div>
As you can see, .\31 .\30
gets parsed into .1.0
, not into .1 .0
. You need two spaces for "normal" CSS space combinator.
Personal advice: don't use numeric classes. It's an unnecessary layer of complexity. You'd be better off with a mapper method, along these lines:
<li :class="[{'favorites': complejosVotes[complejo.id]}, locationClass(complejo.location)]">
methods: {
locationClass(location) {
return location < 5
? 'sm-location'
: location > 10
? 'lg-location'
: 'md-location'
}
}
... which will produce sm-location
class if location value is under 5
, lg-location
if above 10
or md-location
otherwise. Obviously, change the mapper to whatever makes sense for your case.
Upvotes: 1
Reputation: 16069
You can dynamically add a class with the :class=""
attribute. Just pass an object to it, if you want to add a static class on condition. If you want to add a dynamic class (derived from a property), you can just pass it as a value to :class=""
. If you have multiple classes, you want to set, you can use an array and combines these variants. Here is an example in which I assume that you have an object location
and a method isFavorite(locationId)
.
<li :class="[ location.id, { favorite: isFavorite(location.id) } ]"></li>
Upvotes: 2