Vue.js 3嵌套循环中实现表格索引从1递增的方法
Vue3 实现嵌套数组的连续递增索引
下面提供两种实现方式,都能满足你从1开始的连续递增索引需求:
方式一:模板内动态计算索引
直接在模板中通过父级索引和累加前面项的行数来计算当前行的索引,无需修改原数据:
<script src="https://unpkg.com/vue@3.3.4/dist/vue.global.prod.js"></script> <div id="app"> <table border="1"> <thead> <tr> <th>No.</th> <th>Parent</th> <th>Child</th> </tr> </thead> <tbody> <!-- 遍历父级数组,同时获取父项索引 --> <template v-for="(parent, parentIndex) in data" :key="parent.id"> <tr> <!-- 计算父项的索引:前面所有父项的总行数(父行+子行) + 1 --> <td>{{ data.slice(0, parentIndex).reduce((total, item) => total + 1 + item.childs.length, 0) + 1 }}</td> <td>{{ parent.name }}</td> <td></td> </tr> <!-- 遍历子项数组,同时获取子项索引 --> <template v-for="(child, childIndex) in parent.childs" :key="child.id"> <tr> <!-- 计算子项的索引:父项索引 + 子项位置 + 1 --> <td>{{ data.slice(0, parentIndex).reduce((total, item) => total + 1 + item.childs.length, 0) + 1 + childIndex + 1 }}</td> <td></td> <td>{{ child.name }}</td> </tr> </template> </template> </tbody> </table> </div> <script> const { createApp, ref } = Vue const app = createApp({ setup() { const data = [{ id: 1, name: "parent 1", childs: [{ id: 2, name: "child 1-1" }, { id: 10, name: "child 1-2" }] }, { id: 4, name: "parent 2", childs: [{ id: 6, name: "child 2-1" }] }] return { data } }, }).mount('#app') </script>
方式二:预处理数据添加索引
在setup中提前为每个父项和子项计算好索引,模板中直接使用,性能更优(避免模板内重复计算):
<script src="https://unpkg.com/vue@3.3.4/dist/vue.global.prod.js"></script> <div id="app"> <table border="1"> <thead> <tr> <th>No.</th> <th>Parent</th> <th>Child</th> </tr> </thead> <tbody> <template v-for="parent in indexedData" :key="parent.id"> <tr> <td>{{ parent.index }}</td> <td>{{ parent.name }}</td> <td></td> </tr> <template v-for="child in parent.childs" :key="child.id"> <tr> <td>{{ child.index }}</td> <td></td> <td>{{ child.name }}</td> </tr> </template> </template> </tbody> </table> </div> <script> const { createApp, ref } = Vue const app = createApp({ setup() { const rawData = [{ id: 1, name: "parent 1", childs: [{ id: 2, name: "child 1-1" }, { id: 10, name: "child 1-2" }] }, { id: 4, name: "parent 2", childs: [{ id: 6, name: "child 2-1" }] }] // 预处理数据,添加连续索引 const indexedData = ref(rawData.map((parent, parentIdx) => { // 计算当前父项之前的所有行总数 const prevRowCount = rawData.slice(0, parentIdx).reduce((sum, item) => sum + 1 + item.childs.length, 0) return { ...parent, index: prevRowCount + 1, childs: parent.childs.map((child, childIdx) => ({ ...child, index: prevRowCount + 1 + childIdx + 1 })) } })) return { indexedData } }, }).mount('#app') </script>
两种方式最终都会生成如下表格效果:
| No. | Parent | Child |
|---|---|---|
| 1 | parent 1 | |
| 2 | child 1-1 | |
| 3 | child 1-2 | |
| 4 | parent 2 | |
| 5 | child 2-1 |
内容的提问来源于stack exchange,提问作者Tay Zar Aung
相关产品推荐
相关产品推荐

