使用 v-for 上的循环值设置条件类 [英] Using the value of a loop on v-for to set a conditional class
问题描述
我正在使用 v-for"x in y"
生成表格行.我还想根据循环中的值之一设置一些有条件的类.
I'm generating table rows using v-for"x in y"
. I'd also like to set some classes conditional based on one of the values in the loop.
示例:
<tr v-for="file in fileList" class="bg-green if file.include">
<td><% file.filename %></td>
<td><% file.extension %></td>
<td><% file.mime %></td>
</tr>
如果 file.include
是 true
我希望应用 bg-green
类,但它会抛出错误.
If file.include
is true
I'd like the class bg-green
applied, but its throwing an error.
注意:在使用 Flask 时使用自定义分隔符.
note: Using custom delimiters as I'm using Flask.
推荐答案
它只是:
<tr v-for="file in fileList" :class="{'bg-green': file.include}">
:class
是 v-bind:class
的简写形式.需要绑定才能使值成为表达式.
:class
is the shorthand form of v-bind:class
. A binding is necessary to make the value an expression.
有多种方法可以编写表达式,但在这种情况下,最简单的方法是使用对象形式.属性的键是类名,值是确定是否包含该类名的真/假值.
There are several ways to write the expression but in this case the simplest is to use the object form. The keys of the properties are the class names and the values are truthy/falsey values that determine whether or not to include that class name.
替代方案包括:
<tr v-for="file in fileList" :class="file.include ? 'bg-green' : ''">
参见 https://vuejs.org/v2/guide/class-和-style.html 了解更多信息.
See https://vuejs.org/v2/guide/class-and-style.html for more information.
这篇关于使用 v-for 上的循环值设置条件类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!