使用场景效果图如下,需要左右循环出列表中的项目名称和标准
在这里插入图片描述
通过索引,从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 可以解决这个问题 (这也更加明显易读)。

Logo

前往低代码交流专区

更多推荐