3

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?

3 Answers 3

4

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"

Sign up to request clarification or add additional context in comments.

2 Comments

I had already tried with :class="foobar.CssClass", but that didn't yield any result at all. (I should probably have specified that in the question, so I'll do that after this comment)
It seems my error was not passing along the .CssClass from one model to another. I tried recreating it in jsfiddle but no matter what I did it always worked... which lead me to my own models. Thanks for the input :)
1

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>

1 Comment

I had already tried with :class="foobar.CssClass", but that didn't yield any result at all. I also tried with your bracket syntax :class="[foobar.CssClass]" but that didn't yield any results either
1
<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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.