最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - problem creating odd and even cell in a table in Vue Js - Stack Overflow

programmeradmin0浏览0评论

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 badges
Add a ment  | 

2 Answers 2

Reset to default 6

I 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;
}
发布评论

评论列表(0)

  1. 暂无评论