TheHvidsten
TheHvidsten

Reputation: 4418

Append CSS class to element

I have a model, i.e. like this:

[{
    "Name" : "Foo",
    "CssClass" : "class1"
},
{
    "Name" : "Bar",
    "CssClass" : "class2"
}]

Which is presented using the following template:

<li v-for="foobar in model">
    <span class="otherclass anotherclass">{{foobar.Name}}</span>
</li>

How could I append the CssClass property to the span?

I know you could do :class="{ active: isActive }" (as per the documentation), but this uses a predefined class called active, whereas I want to append the class name from the model.

I tried using <span class="otherclass anotherclass" :class="foobar.CssClass"> but that didn't add CssClass to class at all.

How could I go about making this work so that the <span> will effectively be rendered as <span class="otherclass anotherclass class1"> (for the first model entry)? And how could I also use a default value in case CssClass is not defined?

Upvotes: 3

Views: 80

Answers (3)

burak ataseven
burak ataseven

Reputation: 11

<li v-for="foobar in model">
  <span :class="'otherclass anotherclass ' + foobar.CssClass">{{foobar.Name}</span>
</li>

<li v-for="foobar in model">
  <span :class="foobar.CssClass" class="otherclass anotherclass">{{foobar.Name}</span>
</li>

Both should work

Upvotes: 1

pretzelhammer
pretzelhammer

Reputation: 15105

You can pass an object or an array to :class. You can also use class and :class together and Vue will resolve both correctly without issues:

<li v-for="foobar in model">
    <span class="otherclass anotherclass" :class="[foobar.CssClass]">{{foobar.Name}}</span>
</li>

Upvotes: 1

Trevor V
Trevor V

Reputation: 2131

You can append the class like so

<li v-for="foobar in model">
    <span :class="foobar.CssClass" class="otherclass anotherclass">{{foobar.Name}}</span>
</li>

I ran into the same issue in the past. During render all three classes will combine into one class="my_class_from_foobar otherclass anotherclass"

Upvotes: 4

Related Questions