基于vue v-for 多層循環(huán)嵌套獲取行數的方法
在做vue項目的時候難免會用到循環(huán),可是但我們后臺數據返回多條記錄而且是多層嵌套關系的時候,我們需要獲取當前第幾次循環(huán)此時就會出現問題。
下面給大家介紹兩種方式,第一種是基于數學公式:第一次循環(huán)*(第二次循環(huán)總長度)+1+第二次循環(huán) 可以獲取當前第幾次循環(huán)
第二種方法:是在方法中進行計算返回當前下標。廢話不多說先看一下效果吧

具體代碼如下:
測試數據json字符串:
parentList: [{
childList: [{
index: 1,
childName: "第一個節(jié)點"
}, {
index: 2,
childName: "第一個節(jié)點"
}, {
index: 3,
childName: "第一個節(jié)點"
}, {
index: 4,
childName: "第一個節(jié)點"
}, {
index: 5,
childName: "第一個節(jié)點"
}]
},
{
childList: [{
index: 6,
childName: "第二個節(jié)點"
}, {
index: 7,
childName: "第二個節(jié)點"
}, {
index: 8,
childName: "第二個節(jié)點"
}, {
index: 9,
childName: "第二個節(jié)點"
}, {
index: 10,
childName: "第一個節(jié)點"
}]
},
{
childList: [{
index: 11,
childName: "第二個節(jié)點"
}, {
index: 12,
childName: "第二個節(jié)點"
}, {
index: 13,
childName: "第一個節(jié)點"
}, {
index: 14,
childName: "第一個節(jié)點"
}, {
index: 15,
childName: "第一個節(jié)點"
}]
}]
頁面HTML 具體代碼:
<template>
<div class="hello">
<h1>獲取多層循環(huán)的總行數</h1>
<table border="1" width="50%" align="center">
<tr>
<td>父循環(huán)第幾次</td>
<td>子循環(huán)第幾次</td>
<td>第一種辦法</td>
<td>第二種辦法</td>
<td>json字符串中的行數</td>
<td>數值</td>
</tr>
<tbody v-for="parent,index in parentList" :key="index">
<tr v-for="child,cindex in parent.childList" :key="child.index">
<td>{{index}}</td>
<td>{{cindex}}</td>
<td olor="red"> <font size="3" color="red">{{index*(parent.childList.length)+1+cindex}}</font></td>
<td><font size="3" color="red">{{getIndex()}}</font></td>
<td>{{child.index}}</td>
<td>{{child.childName}}</td>
</tr>
</tbody>
</table>
</div>
</template>
第二種獲取下標的方法:
methods:{
getIndex(){
if (!this.index){
this.index=1
}else{
this.index++
}
return this.index
}
}
這樣我們就輕松的獲取到當前循環(huán)第幾行啦。
以上這篇基于vue v-for 多層循環(huán)嵌套獲取行數的方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
詳解vue2.0監(jiān)聽屬性的使用心得及搭配計算屬性的使用
這篇文章主要介紹了vue2.0之監(jiān)聽屬性的使用心得及搭配計算屬性的使用,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2018-07-07
vue2項目如何將webpack遷移為vite并使用svg解決所有bug問題
這篇文章主要介紹了vue2項目如何將webpack遷移為vite并使用svg解決所有bug問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-03-03

