Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding class to element with Vue.JS


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

like image 222
NuzzeSicK Avatar asked May 28 '26 20:05

NuzzeSicK


1 Answers

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>
like image 154
ssc-hrep3 Avatar answered May 30 '26 09:05

ssc-hrep3