IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Java知识库 -> vue2+java8实现多层循环动态添加数据 -> 正文阅读

[Java知识库]vue2+java8实现多层循环动态添加数据

在项目中可能会遇到如下图所示的需求:

遇到这种问题不能着急就码代码,需要冷静的分析它需要什么样的数据结构,一层一层的分析。首先,要循环那自然就是数组(后台封装数据时可以用ArrayList),至于里面的每一层便是一个对象(后台封装数据时可以用HashMap);其次,根据数据结构设计数据库,每一条都在数据库中存一条记录;查询的时候对名称相同的进行分组,然后循环组内数据封装成设定好的数据结构。分析好数据结构之后就可以着手写代码了。

当然你也可以将数据结构进行优化。

前端布局代码如下:

<div style="height:50px;line-height:50px;padding-left:20px;color:#606266;">
            合同回收率:
          <el-button style="right: 40px;top: 0px;" @click="addDomainHTHSL">添加更多</el-button>
        </div>
        <div style="padding:20px 20px 20px 60px;border:1px dashed #ccc;">
        <el-row v-for="(item,i) in form.heTongHuiShouLvs" :key="'info6-'+ i" >
          <el-row>
          <el-col :span="12" style="margin:20px 0 0 250px;">
              <el-form-item label="矿种名" class="rules" :prop="'heTongHuiShouLvs.'+ i + '.kuangZhongName'" :rules="kuangZhongrules.end">
                <el-select v-model="item.kuangZhongName" style="width: 100%">
                  <el-option
                    v-for="item in kuangZhongName"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-button style="margin:20px;" type="primary" size="small" @click="removeHTHSL(item)">移除</el-button>
            </el-col>
          </el-row>
          <el-col :span="24" style="padding:10px;margin:5px 10px;border:1px dashed #ccc;">
              <div v-for="(resItem,j) in item.data" :key="'info7-'+ j" >
                <el-form-item v-for="(ele,index) in resItem.res" :key="'res-'+ index" :label="resItem.name" label-width="60px">
                  <el-col style="text-align:center" :span="1">&gt;</el-col>
                  <el-col :span="3">
                    <el-form-item>
                      <el-input  v-only-number="{ precision: 4 }" v-model="ele.start" ></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col style="text-align:center" :span="1">&lt;=</el-col>
                  <el-col :span="3">
                    <el-form-item>
                      <el-input  v-only-number="{ precision: 4 }" v-model="ele.end"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="7" v-if="resItem.name=='Cu'">
                    <el-form-item label="% 回收率(%)" label-width="100px">
                      <el-input v-only-number="{ precision: 2 }" v-model="ele.percent"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="7" v-if="resItem.name!='Cu'">
                    <el-form-item label="g/dmt 回收率(%)" label-width="120px">
                      <el-input v-only-number="{ precision: 2 }" v-model="ele.percent"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8" v-if="resItem.name=='Cu'">
                    <el-form-item label="品位扣减(%)" label-width="130px">
                      <el-input v-only-number="{ precision: 2 }" v-model="ele.pwkj"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8" v-if="resItem.name!='Cu'">
                    <el-form-item label="品位扣减(g/dmt)" label-width="130px">
                      <el-input v-only-number="{ precision: 2 }" v-model="ele.pwkj"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="1">
                    <template v-if="resItem.name=='Cu'">
                      <el-button type="text" icon="el-icon-plus" style="font-size:16px;" v-if="index==0" @click="addCuRow(resItem)" ></el-button>
                      <el-button type="text" icon="el-icon-minus" style="font-size:16px;" v-if="index!==0" @click="removeCuRow(ele,i)" ></el-button>
                    </template>
                    <template v-if="resItem.name=='Au'">
                      <el-button type="text" icon="el-icon-plus" style="font-size:16px;" v-if="index==0" @click="addAuRow(resItem)" ></el-button>
                      <el-button type="text" icon="el-icon-minus" style="font-size:16px;" v-if="index!==0" @click="removeAuRow(ele,i)" ></el-button>
                    </template>
                    <template v-if="resItem.name=='Ag'">
                      <el-button type="text" icon="el-icon-plus" style="font-size:16px;" v-if="index==0" @click="addAgRow(resItem)" ></el-button>
                      <el-button type="text" icon="el-icon-minus" style="font-size:16px;" v-if="index!==0" @click="removeAgRow(ele,i)" ></el-button>
                    </template>
                  </el-col>
                </el-form-item>
              </div>
          </el-col>
        </el-row>
        </div>

这段代码其实写的并不好,但是循环那个地方可以参考,代码可以自己优化。

前端定义数据结构以及方法:

 //数据
heTongHuiShouLvs: [{
          kuangZhongName: '所有矿种',
          data: [{
            name: 'Cu',
            res: [
              {
                start: '',
                end: '',
                percent: '',
                pwkj: ''
              }
            ]
          },
          {
            name: 'Au',
            res: [
              {
                start: '',
                end: '',
                percent: '',
                pwkj: ''
              }
            ]
          },
          {
            name: 'Ag',
            res: [
              {
                start: '',
                end: '',
                percent: '',
                pwkj: ''
              }
            ]
          }]
        }
        ]
//方法
addDomainHTHSL () {
      this.form.heTongHuiShouLvs.push({
        kuangZhongName: '所有矿种',
        data: [{
          name: 'Cu',
          res: [
            {
              start: '',
              end: '',
              percent: '',
              pwkj: ''
            }
          ]
        },
        {
          name: 'Au',
          res: [
            {
              start: '',
              end: '',
              percent: '',
              pwkj: ''
            }
          ]
        },
        {
          name: 'Ag',
          res: [
            {
              start: '',
              end: '',
              percent: '',
              pwkj: ''
            }
          ]
        }]
      })
    },
    removeHTHSL (item) {
      var index = this.form.heTongHuiShouLvs.indexOf(item)
      if (index !== -1) {
        this.form.heTongHuiShouLvs.splice(index, 3)
      }
    },
addCuRow (val) { // 添加合同回收率--Cu
      val.res.push(
        {
          start: '',
          end: '',
          percent: '',
          pwkj: ''
        }
      )
    },
    removeCuRow (val, index) {
      this.form.heTongHuiShouLvs[index].data.forEach(ele => {
        if (ele.name === 'Cu') {
          var index = ele.res.indexOf(val)
          if (index !== -1) {
            ele.res.splice(index, 1)
          }
        }
      })
    },
    addAuRow (val) { // 添加合同回收率--Au
      val.res.push(
        {
          start: '',
          end: '',
          percent: '',
          pwkj: ''
        }
      )
    },
    removeAuRow (val, index) {
      this.form.heTongHuiShouLvs[index].data.forEach(ele => {
        if (ele.name === 'Au') {
          var index = ele.res.indexOf(val)
          if (index !== -1) {
            ele.res.splice(index, 1)
          }
        }
      })
    },
    addAgRow (val) { // 添加合同回收率--Ag
      val.res.push(
        {
          start: '',
          end: '',
          percent: '',
          pwkj: ''
        }
      )
    },
    removeAgRow (val, index) {
      this.form.heTongHuiShouLvs[index].data.forEach(ele => {
        if (ele.name === 'Ag') {
          var index = ele.res.indexOf(val)
          if (index !== -1) {
            ele.res.splice(index, 1)
          }
        }
      })
    },

后台保存部分代码:

//合同回收率
            List<HeTongHuiShouLvUp> heTongHuiShouLvList = null;
            if (!"".equals(jbj.getString("heTongHuiShouLvs")) && jbj.getString("heTongHuiShouLvs") != null) {
                heTongHuiShouLvList = JSON.parseArray(jbj.getString("heTongHuiShouLvs"), HeTongHuiShouLvUp.class);
            }
            for (int k = 0; k < heTongHuiShouLvList.size(); k++) {
            	HeTongHuiShouLvUp hthslout = heTongHuiShouLvList.get(k);
            	String kzname = hthslout.getKuangZhongName();//每一组的矿种名
            	String hsldata = hthslout.getData();//每一组数据
            	List<HeTongHuiShouLvUp> hsldataList = JSON.parseArray(hsldata, HeTongHuiShouLvUp.class);
            	for (HeTongHuiShouLvUp hthsl : hsldataList) {
 				   String name = hthsl.getName();
 				   if(name.equals("Cu")) {
 					   List<JSONObject> res = JSON.parseArray(hthsl.getRes(), JSONObject.class);
 				    for(int i = 0; i<res.size(); i++) {
 						 double[] Cupercent = new double[res.size()];
 						 double[] Custart = new double[res.size()];
 						 double[] Cuend = new double[res.size()];
 						 double[] Cupwkj = new double[res.size()];
 						 Cupercent[i] = res.get(i).getDouble("percent")==null?0:res.get(i).getDouble("percent");
 						 Custart[i] = res.get(i).getDouble("start")==null?0:res.get(i).getDouble("start");
 						 Cuend[i] = res.get(i).getDouble("end")==null?0:res.get(i).getDouble("end");
 						 Cupwkj[i]= res.get(i).getDouble("pwkj")==null?0:res.get(i).getDouble("pwkj");
 						 HeTongHuiShouLv huiShouLv = new HeTongHuiShouLv();
 						 huiShouLv.sethslType("Cu");
 						 huiShouLv.setShl_CuPercent(Cupercent[i]);
 						 huiShouLv.setShl_CuLower(Custart[i]);
 						 huiShouLv.setShl_CuUpper(Cuend[i]);
 						 huiShouLv.setShl_CuPWKJ(Cupwkj[i]);
 						 huiShouLv.sethTHuiShouLvID(UUIDUtil.uuid());
 						 huiShouLv.setGwHeTongID(heTongId);
 						 huiShouLv.setKuangZhongName(kzname);
 						 heTongHuiShouLvService.save(huiShouLv);
 				    }
 				   }
 				   if(name.equals("Au")) {
 					List<JSONObject> res = JSON.parseArray(hthsl.getRes(), JSONObject.class);
 				    for(int i = 0; i<res.size(); i++) {
 				    	double[] Aupercent = new double[res.size()];
 						double[] Austart = new double[res.size()];
 						double[] Auend = new double[res.size()];
 						double[] Aupwkj = new double[res.size()];
 				        Aupercent[i] = res.get(i).getDouble("percent")==null?0:res.get(i).getDouble("percent");
 				        Austart[i] = res.get(i).getDouble("start")==null?0:res.get(i).getDouble("start");
 				        Auend[i] = res.get(i).getDouble("end")==null?0:res.get(i).getDouble("end");
 				        Aupwkj[i]= res.get(i).getDouble("pwkj")==null?0:res.get(i).getDouble("pwkj");
 				        HeTongHuiShouLv huiShouLv = new HeTongHuiShouLv();
 				        huiShouLv.sethslType("Au");
 				        huiShouLv.setShl_AuPercent(Aupercent[i]);
 					    huiShouLv.setShl_AuLower(Austart[i]);
 					    huiShouLv.setShl_AuUpper(Auend[i]);
 					    huiShouLv.setShl_AuPWKJ(Aupwkj[i]);
 					    huiShouLv.sethTHuiShouLvID(UUIDUtil.uuid());
 					    huiShouLv.setGwHeTongID(heTongId);
 					    huiShouLv.setKuangZhongName(kzname);
 						heTongHuiShouLvService.save(huiShouLv);
 				     }
 				   }
 				   if(name.equals("Ag")) {
 					   List<JSONObject> res = JSON.parseArray(hthsl.getRes(), JSONObject.class);
 				    for(int i = 0; i<res.size(); i++) {
 				    	 double[] Agpercent = new double[res.size()];
 				    	 double[] Agstart = new double[res.size()];
 				    	 double[] Agend = new double[res.size()];
 				    	 double[] Agpwkj = new double[res.size()];
 					     Agpercent[i] = res.get(i).getDouble("percent")==null?0:res.get(i).getDouble("percent");
 					     Agstart[i] = res.get(i).getDouble("start")==null?0:res.get(i).getDouble("start");
 					     Agend[i] = res.get(i).getDouble("end")==null?0:res.get(i).getDouble("end");
 					     Agpwkj[i]= res.get(i).getDouble("pwkj")==null?0:res.get(i).getDouble("pwkj");
 					     HeTongHuiShouLv huiShouLv = new HeTongHuiShouLv();
 					     huiShouLv.sethslType("Ag");
 					     huiShouLv.setShl_AgPercent(Agpercent[i]);
 					     huiShouLv.setShl_AgLower(Agstart[i]);
 					     huiShouLv.setShl_AgUpper(Agend[i]);
 					     huiShouLv.setShl_AgPWKJ( Agpwkj[i]);
 					     huiShouLv.sethTHuiShouLvID(UUIDUtil.uuid());
 					     huiShouLv.setGwHeTongID(heTongId);
 					     huiShouLv.setKuangZhongName(kzname);
 						 heTongHuiShouLvService.save(huiShouLv);
 					}
 				   } 
            	}
 			}

后台查询部分代码:

//合同回收率拼接
                    List fristList = new ArrayList<>();//1
                    String key = "";
                    List<HeTongHuiShouLv> value =  new ArrayList<>();
                    List<HeTongHuiShouLv> hthslList = heTongHuiShouLvService.getHeTongHuiShouLvs(heTongID);//获取每一条记录
                    Map<String, List<HeTongHuiShouLv>> groupByList = hthslList.stream().collect(Collectors.groupingBy(HeTongHuiShouLv::getKuangZhongName));//根据矿种名分组
                    
                    for (Iterator<Entry<String, List<HeTongHuiShouLv>>> it = groupByList.entrySet().iterator(); it.hasNext();) {
                    	HashMap<Object, Object> twoMap = new HashMap<>();//2
                        ArrayList<Object> threeList = new ArrayList<>();//3
                        Entry<String, List<HeTongHuiShouLv>> me = it.next();
                        key = me.getKey();
                        value = me.getValue();
                        
                        /**
                         * key=所有矿种3
value=[HeTongHuiShouLv [hTHuiShouLvID=6231d84a87e44df497bdad19e8e8a864, shl_CuLower=0.0, shl_CuUpper=0.0, shl_CuPercent=0.0, shl_AuLower=0.0, shl_AuUpper=0.0, shl_AuPercent=0.0, shl_AgLower=111.0, shl_AgUpper=111.0, shl_AgPercent=11.0, gwHeTongID=null, gwDingDanID=null, gwBaoPanID=null, jieSuanDanHao=null, hslType=null, bak2=null, shl_CuPWKJ=0.0, shl_AuPWKJ=0.0, shl_AgPWKJ=1.0, kuangZhongName=所有矿种3, kuangZhongID=null]]
                         */
                        HashMap<Object, Object> fourMapCu = new HashMap<>();//4
                        HashMap<Object, Object> fourMapAu = new HashMap<>();//4
                        HashMap<Object, Object> fourMapAg = new HashMap<>();//4
                        ArrayList<Object> fiveListCu = new ArrayList<>();//5
                        ArrayList<Object> fiveListAu = new ArrayList<>();//5
                        ArrayList<Object> fiveListAg = new ArrayList<>();//5
                        for (HeTongHuiShouLv hthsl:value) {//循环每个分组
                            System.out.println(hthsl);
                            Map<String, Object> Cumap = new HashMap<>();//6
                            Map<String, Object> Aumap = new HashMap<>();//6
                            Map<String, Object> agmap = new HashMap<>();//6
                            if("Cu".equals(hthsl.gethslType())) {
	                            Cumap.put("start", hthsl.getShl_CuLower());
	                            Cumap.put("end", hthsl.getShl_CuUpper());
	                            Cumap.put("percent", hthsl.getShl_CuPercent());
	                            Cumap.put("pwkj", hthsl.getShl_CuPWKJ());
	                            fiveListCu.add(Cumap);
                            }
                            if("Au".equals(hthsl.gethslType())) {
	                            Aumap.put("start", hthsl.getShl_AuLower());
	                            Aumap.put("end", hthsl.getShl_AuUpper());
	                            Aumap.put("percent", hthsl.getShl_AuPercent());
	                            Aumap.put("pwkj", hthsl.getShl_AuPWKJ());
	                            fiveListAu.add(Aumap);
                            }
                            if("Ag".equals(hthsl.gethslType())) {
	                            agmap.put("start", hthsl.getShl_AgLower());
	                            agmap.put("end", hthsl.getShl_AgUpper());
	                            agmap.put("percent", hthsl.getShl_AgPercent());
	                            agmap.put("pwkj", hthsl.getShl_AgPWKJ());
	                            fiveListAg.add(agmap);
                            }
                        }
                        if(fiveListCu.size()>0) {
                        	fourMapCu.put("name", "Cu");
                            fourMapCu.put("res", fiveListCu);
                        }else {
                        	Map<String, Object> map = new HashMap<>();//6
                        	map.put("start", 0.0000);
                        	map.put("end", 0.0000);
                        	map.put("percent", 0.0000);
                        	map.put("pwkj", 0.0000);
                            fiveListCu.add(map);
                        	fourMapCu.put("name", "Cu");
                            fourMapCu.put("res", fiveListCu);
                        }
                        if(fiveListAu.size()>0) {
                        	fourMapAu.put("name", "Au");
                            fourMapAu.put("res", fiveListAu);
                        }else {
                        	Map<String, Object> map = new HashMap<>();//6
                        	map.put("start", 0.0000);
                        	map.put("end", 0.0000);
                        	map.put("percent", 0.0000);
                        	map.put("pwkj", 0.0000);
                        	fiveListAu.add(map);
                            fourMapAu.put("name", "Au");
                            fourMapAu.put("res", fiveListAu);
                        }
                        if(fiveListAg.size()>0) {
                        	fourMapAg.put("name", "Ag");
                            fourMapAg.put("res", fiveListAg);
                        }else {
                        	Map<String, Object> map = new HashMap<>();//6
                        	map.put("start", 0.0000);
                        	map.put("end", 0.0000);
                        	map.put("percent", 0.0000);
                        	map.put("pwkj", 0.0000);
                        	fiveListAg.add(map);
                            fourMapAg.put("name", "Ag");
                            fourMapAg.put("res", fiveListAg);
                        }
                        threeList.add(fourMapCu);
                        threeList.add(fourMapAu);
                        threeList.add(fourMapAg);
                        twoMap.put("kuangZhongName", key);
                        twoMap.put("data", threeList);
                        fristList.add(twoMap);
                    }

以上是嵌套循环的情况,如果只需要内部那一部分,就很简单啦,参考内部循环就可以,哈哈哈。

代码优化部分还希望大家多多指导,必定虚心学习,期待共同进步。

  Java知识库 最新文章
计算距离春节还有多长时间
系统开发系列 之WebService(spring框架+ma
springBoot+Cache(自定义有效时间配置)
SpringBoot整合mybatis实现增删改查、分页查
spring教程
SpringBoot+Vue实现美食交流网站的设计与实
虚拟机内存结构以及虚拟机中销毁和新建对象
SpringMVC---原理
小李同学: Java如何按多个字段分组
打印票据--java
上一篇文章      下一篇文章      查看所有文章
加:2021-07-10 14:24:43  更:2021-07-10 14:26:08 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/17 20:24:49-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码