I have a vue function that is currently using nested v-for loops to iterate an object and build a table with rows an cells accordingly. This is working, but I need to figure out how to get a v-if into the most nested part now and look at the discarded value in order to set conditional styling.
Basically, for each td element, I want to check tests.discarded, and if the number in that field is greater than 0, then color the cell red. Else, color it green
How can I achieve this with the current state of my code? I can't use a v-if in my most nested v-for element
namestest: [
name: "john",
date: "08/12/21",
discarded: 4,
count: 19
]
<tr v-for="(tests, name) in namestest" :key="name">
<td>@{{ name }}</td>
//each time i iterate through it, it should check the discarded field and see if greather than 0. If so, then we color the cell red
<td v-for="date in dates" :key="date">@{{ tests[date] && tests[date].count }}</td>
</tr>
There's no need to use v-if for applying styles conditionally:
<td :style="'background: ' + (tests.discarded > 0 ? 'red' : 'green')">@{{ name }}</td>
You can obviously use @slauth solution with inline expression inside the style attribute or you can create a method/function.
Whether you're using Option API or Composition API just define your function which would accept a parameter (discarded). You can even define multiple methods, one for styling color and the other for conditional rendering the text.
Finally for inline conditions you can always use <template v-if="something"> anything between template tags will be rendered and template tags will disappear.
You could do it like this:
<td>@{{ name }}</td>
<td v-for="date in dates" :style="'background: ' + (tests[date].discarded > 0 ? 'red' : 'blue')" :key="date">@{{ tests[date] && tests[date].count }}</td>
And use a conditional inline style. Or, you could put the conditional in the binding of class, instead of the style attribute. Like
<td v-for="date in dates" :class="{ badcell: (tests[date].discarded > 0) }">@{{ tests[date] && tests[date].count }}</td>
This way, the class badcell will only be applied if discarded is greater than 0. And then have a style for the new 'badcell' class in your CSS or SCSS.
td.badcell {
background-color:red;
font-weight:bold;
}