vue使用v-for循环一次循环两项

本文介绍如何在模板中通过v-for和v-if组合循环列表,确保偶数索引项与相邻奇数项的交替显示,并避免v-if和v-for混用带来的问题。代码实例和注意事项详细解析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用场景效果图如下,需要左右循环出列表中的项目名称和标准
在这里插入图片描述
通过索引,从0开始通过v-if循环出偶数索引的条件项,在偶数索引+1得到奇数项。
代码如下:

<template v-for="(item, index) in form.selectedInspectionItem">
    <tr style="height:40px" :key="index" v-if="index%2==0">
        <td colspan="2">{{item.name}}</td>
        <td colspan="3">{{item.standardNo}}</td>
        <td colspan="2">{{form.selectedInspectionItem[index+1].name}}</td>
        <td colspan="3">{{form.selectedInspectionItem[index+1].standardNo}}</td>
    </tr>
</template>

另外,还有一点需要注意,同时使用 v-if 和 v-for 是不推荐的,因为这样二者的优先级不明显。当 v-if 和 v-for 同时存在于一个元素上的时候,v-if 会首先被执行,这意味着 v-if 的条件将无法访问到 v-for 作用域内定义的变量别名:

<!--
 这会抛出一个错误,因为属性 index 此时
 没有在该实例上定义
-->
<tr style="height:40px" v-for="(item, index) in form.selectedInspectionItem" :key="index" v-if="index%2==0">
    <td colspan="2">{{item.name}}</td>
    <td colspan="3">{{item.standardNo}}</td>
    <td colspan="2">{{form.selectedInspectionItem[index+1].name}}</td>
    <td colspan="3">{{form.selectedInspectionItem[index+1].standardNo}}</td>
</tr>

在外新包装一层 再在其上使用 v-for 可以解决这个问题 (这也更加明显易读)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值