当前位置: 移动技术网 > IT编程>脚本编程>vue.js > 基于vue v-for 多层循环嵌套获取行数的方法

基于vue v-for 多层循环嵌套获取行数的方法

2019年06月02日  | 移动技术网IT编程  | 我要评论

斗鱼莉爷,哈密壹周刊,QQ腾轩乐园

在做vue项目的时候难免会用到循环,可是但我们后台数据返回多条记录而且是多层嵌套关系的时候,我们需要获取当前第几次循环此时就会出现问题。

下面给大家介绍两种方式,第一种是基于数学公式:第一次循环*(第二次循环总长度)+1+第二次循环 可以获取当前第几次循环

第二种方法:是在方法中进行计算返回当前下标。废话不多说先看一下效果吧

vue v-for 多层循环嵌套

具体代码如下:

测试数据json字符串:

parentlist: [{
   childlist: [{
   index: 1,
   childname: "第一个节点"
   }, {
   index: 2,
   childname: "第一个节点"
   }, {
   index: 3,
   childname: "第一个节点"
   }, {
   index: 4,
   childname: "第一个节点"
   }, {
   index: 5,
   childname: "第一个节点"
   }]
  },
   {
   childlist: [{
    index: 6,
    childname: "第二个节点"
   }, {
    index: 7,
    childname: "第二个节点"
   }, {
    index: 8,
    childname: "第二个节点"
   }, {
    index: 9,
    childname: "第二个节点"
   }, {
    index: 10,
    childname: "第一个节点"
   }]
   },
   {
   childlist: [{
    index: 11,
    childname: "第二个节点"
   }, {
    index: 12,
    childname: "第二个节点"
   }, {
    index: 13,
    childname: "第一个节点"
   }, {
    index: 14,
    childname: "第一个节点"
   }, {
    index: 15,
    childname: "第一个节点"
   }]
   }]

页面html 具体代码:

<template>
 <div class="hello">
 <h1>获取多层循环的总行数</h1>
 <table border="1" width="50%" align="center">
  <tr>
  <td>父循环第几次</td>
  <td>子循环第几次</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
  }
 }

这样我们就轻松的获取到当前循环第几行啦。

以上这篇基于vue v-for 多层循环嵌套获取行数的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网