您好,登錄后才能下訂單哦!
在做vue項(xiàng)目的時(shí)候難免會用到循環(huán),可是但我們后臺數(shù)據(jù)返回多條記錄而且是多層嵌套關(guān)系的時(shí)候,我們需要獲取當(dāng)前第幾次循環(huán)此時(shí)就會出現(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"> <h2>獲取多層循環(huán)的總行數(shù)</h2> <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è)參考,也希望大家多多支持億速云。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。