簡體   English   中英

將 CSS 類附加到元素

[英]Append CSS class to element

我有一個模型,即這樣的:

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

使用以下模板呈現:

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

如何將CssClass屬性附加到跨度?

我知道你可以這樣做:class="{ active: isActive }" (根據文檔),但這使用了一個名為active的預定義類,而我想從模型中附加類名。

我嘗試使用<span class="otherclass anotherclass" :class="foobar.CssClass">但這根本沒有將CssClass添加到class中。

我該如何着手進行這項工作,以便<span>將有效地呈現為<span class="otherclass anotherclass class1"> (對於第一個模型條目)? 如果CssClass沒有定義,我怎么能使用默認值呢?

您可以像這樣附加課程

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

我過去遇到過同樣的問題。 在渲染期間,所有三個類將合並為一個class="my_class_from_foobar otherclass anotherclass"

您可以將對象或數組傳遞給:class 您還可以同時使用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>

兩者都應該工作

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM