Here is my code, myData is my vue data model which has some field: a,b, ... odd-cell and even-cell are the CSS classes with different background color. its a foreach loop, how can i calcultate something like if (length of myData % 2 == 1) in v-if to add the odd and even class in my div.
<div v-for="item in myData">
<div v-if="" class='odd-cell'>
<p> {{item.a}} </p>
<p> {{item.b}} </p>
</div>
<div v-else class='even-cell'>
<p> {{item.a}} </p>
<p> {{item.b}} </p>
</div>
</div>
[i am writing in cshtml view page, so you can suggest c# code as well..]
Here is my code, myData is my vue data model which has some field: a,b, ... odd-cell and even-cell are the CSS classes with different background color. its a foreach loop, how can i calcultate something like if (length of myData % 2 == 1) in v-if to add the odd and even class in my div.
<div v-for="item in myData">
<div v-if="" class='odd-cell'>
<p> {{item.a}} </p>
<p> {{item.b}} </p>
</div>
<div v-else class='even-cell'>
<p> {{item.a}} </p>
<p> {{item.b}} </p>
</div>
</div>
[i am writing in cshtml view page, so you can suggest c# code as well..]
Share Improve this question asked Nov 21, 2018 at 4:50 TanvirAhmedKhanTanvirAhmedKhan 294 bronze badges2 Answers
Reset to default 6I refered to a UI framework which now I'm using, name as iView.
Of course, they also support striped table ponent. So I wondered how they do like that.
.ivu-table-stripe .ivu-table-body tr:nth-child(2n) td,
.ivu-table-stripe .ivu-table-fixed-body tr:nth-child(2n) td {
background-color: #f8f8f9;
}
As you can see, CSS support for handling each case of even and odd by using nth-child()
. There is no more simple way to do like that.
further more, you can use more plex formula as a parameter like this :
(an + b).
W3School Nth-child Example maybe helpful for you.
You can use index
:
<div v-for="(item, index) in myData">
<div v-if="" :class="{'odd-cell': index % 2 === 1, 'even-cell': index % 2 === 0}">
<p> {{item.a}} </p>
<p> {{item.b}} </p>
</div>
</div>
But there are better solution with css nth-child
div:nth-child(odd) {
background: red;
}
div:nth-child(even) {
background: blue;
}