前台:
//添加树形菜单控件
<a-tree show-line :treeData="treeData">
<a-icon slot="switcherIcon" type="down" />
</a-tree>
//在data中定义数据源
treeData:'',
//请求数据方法
getTree(){
let params = '';
getAction('/department/subDepartment/getTree', params).then((res) => {
if (res.success) {
this.treeData = res.result;
}
if(res.code===510){
this.$message.warning(res.message)
}
this.loading = false;
})
}
后台返回树形json数据
public Result<?> getTree(HttpServletRequest req) {
List<SubDepartment> list = subDepartmentService.list();
List<SubDepartment> treeList = new ArrayList<>();
for(SubDepartment subDepartment:list){
if(subDepartment.getParentId().equals("0")){
subDepartment.setTitle(subDepartment.getSubDepName());
subDepartment.setKey(subDepartment.getId());
subDepartment.setChildren(subDepartmentService.getChildrenTree(subDepartment.getId(),list));
treeList.add(subDepartment);
}
}
Result result = new Result();
result.setResult(treeList);
result.setSuccess(true);
return result;
}
@Override
public List<SubDepartment> getChildrenTree(String id, List<SubDepartment> subDepartmentList) {
List<SubDepartment> newTree = new ArrayList<>();
for(SubDepartment subDepartment:subDepartmentList){
if(subDepartment.getParentId().equals("0")){
continue;
}
subDepartment.setTitle(subDepartment.getSubDepName());
subDepartment.setKey(subDepartment.getId());
if(id.equals(subDepartment.getParentId())){
//递归获取子节点下的子节点
subDepartment.setChildren(getChildrenTree(subDepartment.getId(),subDepartmentList));
newTree.add(subDepartment);
}
}
return newTree;
}
实体类中需要包含key和title字段。
参考链接:https://blog.csdn.net/weixin_42528855/article/details/116259541