树形数据的无限级别(递归实现)

树形数据的菜单路由无限级别(递归实现)

从后台获取到数据根据前端的需要重组数据,因为后端没有component所以得依据后端数据匹配前端的路由拿到component

下面是两个模拟的数据

// 模拟后端的数据
	let ceshi = [
					{
						 name: '电脑',
						 val:'a',
						 children: [
						     {
						         name: 'F盘',
								 val:'b',
								children:[
									{
										name: '照片',
										val: 'c',
										children:[
											{
												name: '照片1',
												val: 'c1',
												children:[
													{
														name: '照片2',
														val: 'c2',
														children:[
															{
																name: '照片3',
																val: 'c3',
															},
															{
																name: '照片4',
																val: 'c4',
															}
														]
													}
												]
											}
										]
									}
								]
							 },
						]
					},
					{
						 name: 'E盘',
						 val:'d',
					    children:[
							{
								 name: 'bb',
								 val:'f',
								 key:'5',
							    children:[
									{
										 name: 'bb',
										 val:'f',
										 key:'5',
									    children:[]
									}
								]
							}
						]
					}
				];

//模拟前端的数据
key代表component
	let ceshi1 = [{
				    name: '电脑',
					val:'a',
					key:'1',
				    children: [
				        {
				            name: 'F盘',
							 val:'b',
							 key:'2',
				            children: [
				                {
				                    name: '照片',
									 val:'c',
									 key:'3',
				                    children:[
				                    	{
				                    		name: '照片1',
				                    		val: 'c1',
											key:'4',
				                    		children:[
				                    			{
				                    				name: '照片2',
				                    				val: 'c2',
													key:'5',
				                    				children:[
				                    					{
				                    						name: '照片3',
				                    						val: 'c5',
															key:'6',
				                    					},
														{
															name: '照片4',
															val: 'c4',
															key:'7',
														}
				                    				]
				                    			}
				                    		]
				                    	}
				                    ]
				                },
				            ]
				        }
				    ]},
					{
					    name: 'E盘',
						val:'d',
						key:'4',
						children:[
							{
								 name: 'bb',
								 val:'f',
								 key:'5',
							    children:[
									{
										 name: 'bb',
										 val:'f',
										 key:'5',
									    children:[]
									}
								]
							}
						]
					},
					{
						 name: 'bb',
						 val:'f',
						 key:'5',
					    children:[]
					}
				]
数据都准备完成,下面是递归的方法,不知道为什么 第一个chong递归的方法就已经完成了能把key都赋值上去了,但有时候会把所有数据返回来,但是里面没有key。为了解决这个所以我又用了again这个递归把没有key的去掉,这样就是前端需要展示的路由数据了。
function chong(root,yuanshi){
					if(root.length<=0) return;
					for(let i=0;i<root.length;i++){
						for(let j=0;j<yuanshi.length;j++){
							if(root[i].val === yuanshi[j].val){
								if(root[i].children&&root[i].children.length>0){
								  chong(root[i].children,yuanshi[j].children)
								}
								// console.log(root[i].val,"root[j]")
								root[i].key = yuanshi[j].key;
							}
							
						}
						
					}
				}
				chong(ceshi,ceshi1);
				function again(root) {
					if(root.length<=0) return;
					root.forEach((item,index)=>{
						if(item.children&&item.children.length>0){
							again(item.children)
						}
						if(!item.key){root.splice(index,1)}
					})
				}
				again(ceshi);
				console.log(ceshi,"ceshi1")

这是打出来的结果(我把照片3的val后台模拟是c3 前端是c5,两个不相等所以我把没要的去掉了);这样就可以动态设置数据了

在这里插入图片描述
下面是实际项目中的 这是用在后台管理系统上的vueX里面的

      routers(store,data){
            return new Promise((resolve,reject)=>{
                allowMenuList().then(res=>{
                    res.data.sort(function (a,b) {
                        return (+a.sid)-(+b.sid);
                    })
                    function chong(root,yuanshi){
                        if(root.length<=0) return;
                        for(let i=0;i<root.length;i++){
                            for(let j=0;j<yuanshi.length;j++){
                                if(root[i].name === yuanshi[j].name){
                                    if(root[i].children&&root[i].children.length>0){
                                        chong(root[i].children,yuanshi[j].children)
                                    }
                                    // console.log(root[i].val,"root[j]")
                                    root[i] = yuanshi[j];
                                }

                            }

                        }
                    }
                    chong(res.data,routes);
                    function again(root) {
                        if(root.length<=0) return;
                        root.forEach((item,index)=>{
                            if(item.children&&item.children.length>0){
                                again(item.children)
                            }
                            if(!item.component){root.splice(index,1)}
                        })
                    }
                    again(res.data);
                    let arr = [];
                    arr = res.data; //这是最终的数据
                    store.commit('routers', arr);
                    resolve(arr)
                }).catch(err=>{
                    reject(err)
                })
            })
        },

这是实际项目中的效果
在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
无限级树(Java递归) 2007-02-08 10:26 这几天,用java写了一个无限极的树,递归写的,可能代码不够简洁,性能不够好,不过也算是练习,这几天再不断改进。前面几个小图标的判断,搞死我了。 package com.nickol.servlet; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.nickol.utility.DB; public class category extends HttpServlet { /** * The doGet method of the servlet. * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("utf-8"); response.setContentType("text/html"); PrintWriter out = response.getWriter(); out .println(""); out.println(""); out.println(" Category" + "" + "body{font-size:12px;}" + "" + "" + ""); out.println(" "); out.println(showCategory(0,0,new ArrayList(),"0")); out.println(" "); out.println(""); out.flush(); out.close(); } public String showCategory(int i,int n,ArrayList frontIcon,String countCurrent){ int countChild = 0; n++; String webContent = new String(); ArrayList temp = new ArrayList(); try{ Connection conn = DB.GetConn(); PreparedStatement ps = DB.GetPs("select * from category where pid = ?", conn); ps.setInt(1, i); ResultSet rs = DB.GetRs(ps); if(n==1){ if(rs.next()){ webContent += "";//插入结尾的减号 temp.add(new Integer(0)); } webContent += " ";//插入站点图标 webContent += rs.getString("cname"); webContent += "\n"; webContent += showCategory(Integer.parseInt(rs.getString("cid")),n,temp,"0"); } if(n==2){ webContent += "\n"; }else{ webContent += "\n"; } while(rs.next()){ for(int k=0;k<frontIcon.size();k++){ int iconStatic = ((Integer)frontIcon.get(k)).intValue(); if(iconStatic == 0){ webContent += "";//插入空白 }else if(iconStatic == 1){ webContent += "";//插入竖线 } } if(rs.isLast()){ if(checkChild(Integer.parseInt(rs.getString("cid")))){ webContent += "";//插入结尾的减号 temp = (ArrayList)frontIcon.clone(); temp.add(new Integer(0)); }else{ webContent += "";//插入结尾的直角 } }else{ if(checkChild(Integer.parseInt(rs.getString("cid")))){ webContent += "";//插入未结尾的减号 temp = (ArrayList)frontIcon.clone(); temp.add(new Integer(1)); }else{ webContent += "";//插入三叉线 } } if(checkChild(Integer.parseInt(rs.getString("cid")))){ webContent += " ";//插入文件夹图标 }else{ webContent += " ";//插入文件图标 } webContent += rs.getString("cname"); webContent += "\n"; webContent += showCategory(Integer.parseInt(rs.getString("cid")),n,temp,countCurrent+countChild); countChild++; } webContent += "\n"; DB.CloseRs(rs); DB.ClosePs(ps); DB.CloseConn(conn); }catch(Exception e){ e.printStackTrace(); } return webContent; } public boolean checkChild(int i){ boolean child = false; try{ Connection conn = DB.GetConn(); PreparedStatement ps = DB.GetPs("select * from category where pid = ?", conn); ps.setInt(1, i); ResultSet rs = DB.GetRs(ps); if(rs.next()){ child = true; } DB.CloseRs(rs); DB.ClosePs(ps); DB.CloseConn(conn); }catch(Exception e){ e.printStackTrace(); } return child; } } --------------------------------------------------------------------- tree.js文件 function changeState(countCurrent,countChild){ var object = document.getElementById("level" + countCurrent + countChild); if(object.style.display=='none'){ object.style.display='block'; }else{ object.style.display='none'; } var cursor = document.getElementById("cursor" + countCurrent + countChild); if(cursor.src.indexOf("images/tree_minus.gif")>=0) {cursor.src="images/tree_plus.gif";} else if(cursor.src.indexOf("images/tree_minusbottom.gif")>=0) {cursor.src="images/tree_plusbottom.gif";} else if(cursor.src.indexOf("images/tree_plus.gif")>=0) {cursor.src="images/tree_minus.gif";} else {cursor.src="images/tree_minusbottom.gif";} var folder = document.getElementById("folder" + countCurrent + countChild); if(folder.src.indexOf("images/icon_folder_channel_normal.gif")>=0){ folder.src = "images/icon_folder_channel_open.gif"; }else{ folder.src = "images/icon_folder_channel_normal.gif"; }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值