Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 341
GTHvidsten Avatar asked Sep 10 '26 14:09

GTHvidsten


1 Answers

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"

like image 112
Trevor V Avatar answered Sep 12 '26 02:09

Trevor V



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!