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

具體代碼如下:
測試數(shù)據(jù)json字符串:
parentList: [{
childList: [{
index: 1,
childName: "第一個(gè)節(jié)點(diǎn)"
}, {
index: 2,
childName: "第一個(gè)節(jié)點(diǎn)"
}, {
index: 3,
childName: "第一個(gè)節(jié)點(diǎn)"
}, {
index: 4,
childName: "第一個(gè)節(jié)點(diǎn)"
}, {
index: 5,
childName: "第一個(gè)節(jié)點(diǎn)"
}]
},
{
childList: [{
index: 6,
childName: "第二個(gè)節(jié)點(diǎn)"
}, {
index: 7,
childName: "第二個(gè)節(jié)點(diǎn)"
}, {
index: 8,
childName: "第二個(gè)節(jié)點(diǎn)"
}, {
index: 9,
childName: "第二個(gè)節(jié)點(diǎn)"
}, {
index: 10,
childName: "第一個(gè)節(jié)點(diǎn)"
}]
},
{
childList: [{
index: 11,
childName: "第二個(gè)節(jié)點(diǎn)"
}, {
index: 12,
childName: "第二個(gè)節(jié)點(diǎn)"
}, {
index: 13,
childName: "第一個(gè)節(jié)點(diǎn)"
}, {
index: 14,
childName: "第一個(gè)節(jié)點(diǎn)"
}, {
index: 15,
childName: "第一個(gè)節(jié)點(diǎn)"
}]
}]
頁面HTML 具體代碼:
<template>
<div class="hello">
<h1>獲取多層循環(huán)的總行數(shù)</h1>
<table border="1" width="50%" align="center">
<tr>
<td>父循環(huán)第幾次</td>
<td>子循環(huán)第幾次</td>
<td>第一種辦法</td>
<td>第二種辦法</td>
<td>json字符串中的行數(shù)</td>
<td>數(shù)值</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>
第二種獲取下標(biāo)的方法:
methods:{
getIndex(){
if (!this.index){
this.index=1
}else{
this.index++
}
return this.index
}
}
這樣我們就輕松的獲取到當(dāng)前循環(huán)第幾行啦。
以上這篇基于vue v-for 多層循環(huán)嵌套獲取行數(shù)的方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Vue3 directive自定義指令內(nèi)部實(shí)現(xiàn)示例
這篇文章主要為大家介紹了Vue3 directive自定義指令內(nèi)部實(shí)現(xiàn)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-12-12
VUE接入騰訊驗(yàn)證碼功能(滑塊驗(yàn)證)備忘
這篇文章主要介紹了VUE接入騰訊驗(yàn)證碼功能(滑塊驗(yàn)證)備忘,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-05-05
vue計(jì)算屬性時(shí)v-for處理數(shù)組時(shí)遇到的一個(gè)bug問題
這篇文章主要介紹了在做vue計(jì)算屬性,v-for處理數(shù)組時(shí)遇到的一個(gè)bug 問題,需要的朋友可以參考下2018-01-01
webpack搭建vue環(huán)境時(shí)報(bào)錯(cuò)異常解決
這篇文章主要介紹了webpack搭建vue環(huán)境時(shí)報(bào)錯(cuò)異常解決,本篇文章通過簡要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-09-09

