基于vue v-for 多層循環(huán)嵌套獲取行數(shù)的方法
在做vue項目的時候難免會用到循環(huán),可是但我們后臺數(shù)據(jù)返回多條記錄而且是多層嵌套關(guān)系的時候,我們需要獲取當(dāng)前第幾次循環(huán)此時就會出現(xiàn)問題。
下面給大家介紹兩種方式,第一種是基于數(shù)學(xué)公式:第一次循環(huán)*(第二次循環(huán)總長度)+1+第二次循環(huán) 可以獲取當(dāng)前第幾次循環(huán)
第二種方法:是在方法中進(jìn)行計算返回當(dāng)前下標(biāo)。廢話不多說先看一下效果吧
具體代碼如下:
測試數(shù)據(jù)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)的總行數(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)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
詳解vue2.0監(jiān)聽屬性的使用心得及搭配計算屬性的使用
這篇文章主要介紹了vue2.0之監(jiān)聽屬性的使用心得及搭配計算屬性的使用,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2018-07-07vue2項目如何將webpack遷移為vite并使用svg解決所有bug問題
這篇文章主要介紹了vue2項目如何將webpack遷移為vite并使用svg解決所有bug問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-03-03vue頁面回退或關(guān)閉,發(fā)送請求不中斷問題
這篇文章主要介紹了vue頁面回退或關(guān)閉,發(fā)送請求不中斷問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-01-01vue路由結(jié)構(gòu)可設(shè)一層方便動態(tài)添加路由操作
這篇文章主要介紹了vue路由結(jié)構(gòu)可設(shè)一層方便動態(tài)添加路由操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-08-08淺談Vue網(wǎng)絡(luò)請求之interceptors實際應(yīng)用
這篇文章主要介紹了淺談Vue網(wǎng)絡(luò)請求之interceptors實際應(yīng)用,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-02-02vue內(nèi)置組件transition簡單原理圖文詳解(小結(jié))
這篇文章主要介紹了vue內(nèi)置組件transition簡單原理圖文詳解(小結(jié)),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-07-07