[英]Append CSS class to element
I have a model, ie 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?如何将
CssClass
属性附加到跨度?
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.我知道你可以这样做
:class="{ active: isActive }"
(根据文档),但这使用了一个名为active
的预定义类,而我想从模型中附加类名。
I tried using <span class="otherclass anotherclass" :class="foobar.CssClass">
but that didn't add CssClass
to class
at all.我尝试使用
<span class="otherclass anotherclass" :class="foobar.CssClass">
但这根本没有将CssClass
添加到class
中。
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)?我该如何着手进行这项工作,以便
<span>
将有效地呈现为<span class="otherclass anotherclass class1">
(对于第一个模型条目)? And how could I also use a default value in case CssClass
is not defined?如果
CssClass
没有定义,我怎么能使用默认值呢?
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"
在渲染期间,所有三个类将合并为一个
class="my_class_from_foobar otherclass anotherclass"
You can pass an object or an array to :class
.您可以将对象或数组传递给
:class
。 You can also use class
and :class
together and Vue will resolve both correctly without issues:您还可以同时使用
class
和:class
,Vue 将正确解决这两个问题:
<li v-for="foobar in model">
<span class="otherclass anotherclass" :class="[foobar.CssClass]">{{foobar.Name}}</span>
</li>
<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两者都应该工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.