Ari
Ari

Reputation: 6189

Using the value of a loop on v-for to set a conditional class

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.

example:

<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>

If file.include is true I'd like the class bg-green applied, but its throwing an error.

note: Using custom delimiters as I'm using Flask.

Upvotes: 0

Views: 88

Answers (1)

skirtle
skirtle

Reputation: 29122

It'd just be:

<tr v-for="file in fileList" :class="{'bg-green': file.include}">

: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.

Alternatives include things like:

<tr v-for="file in fileList" :class="file.include ? 'bg-green' : ''">

See https://v2.vuejs.org/v2/guide/class-and-style.html for more information.

Upvotes: 1

Related Questions