后台:
前端需要的数据格式如下,即需要在后台构建这种格式的数据:
treeData:[
{
label:"",
children:
[
{label:"",children:[{...}]}
]
}
]
1.查询根节点:
public List<Map> taxTreeList(String taxcode){
List<Map> mapList = new ArrayList<Map>();
//查询根节点
List<TaxCode> list = productMapper.taxTreeListByCode(taxcode);
for(TaxCode taxcode1:list){
mapList.add(this.selctSonList(taxcode1));
}
return mapList;
}
2.根据父节点查询子节点
public Map selctSonList(TaxCode taxcode){
Map map = new HashMap();
map.put("label",taxcode.getTaxcode());
//根据父节点查询子节点
List<TaxCode> list = productMapper.taxTreeListByCode(taxcode.getTaxcode());
if(list.size()>0){
List<Map> list1 = new ArrayList<Map>();
for(TaxCode tax:list){
//根据父节点查询子节点
list1.add(this.selctSonList(tax));
}
map.put("children",list1);
};
return map;
}
前端:
vue页面:
<el-tree ref="tree" :data="treeData" :props="props">
<span class="span-ellipsis" slot-scope="{node,data}">
<span :title="data.label" style="font-size: 14px;">{{data.label}}</span>
</span>
</el-tree>
·treeData为后台返回的数据;
·label为树形结构展示的内容
效果如下图:
------------------------------------分割线--------------------------------
以上方法是需要多次调用数据库的,更新一个一次性查询数据然后用集合去循环的,逻辑跟上面差不多~
public List<Map> taxTreeList(){
//访问数据库
List<Map> l = testMapper.getList();
List<Map> list = new ArrayList<>();
for(int i=0;i<l.size();i++){
//获取每一个根节点的id
if(Long.parseLong(l.get(i).get("pid").toString())==0){
list.add(this.getList(l,l.get(i)));
}
}
return list;
}
//m表示父节点对象
public Map getList(List<Map> l,Map m){
Map map = new HashMap();
map.put("label",m.get("name"));
//根据父节点id获取子节点
List<Map> list = new ArrayList<>();
for(int i=0;i<l.size();i++){
if(m.get("id").toString().equals(l.get(i).get("pid").toString())){
list.add(this.getList(l,l.get(i)));
}
map.put("children",list);
}
return map;
}