一、后端树形逻辑处理
代码如下:
/**
* 条件查询,返回该节点及其所有祖父节点,并转换成树形返回
*
* @param searchVO 查询条件
* @return 树
*/
@Override
public List<FoodTreeVo> treeSearch(FoodTreeVo searchVO) {
// 条件
Wrapper<Food> searchWrapper = Condition.wrapper();
// id
searchWrapper.eq(searchVO.getId() != null, Food.ID, searchVO.getId());
// 编号
searchWrapper.like(searchVO.getCode() != null, Food.CODE, searchVO.getCode());
// 名称
searchWrapper.like(searchVO.getName() != null, Food.NAME, searchVO.getName());
// 列表数据
List<Food> list = null;
if (searchWrapper.isNotEmptyOfWhere()) {
// 条件查询
List<Food> nodes = this.selectList(searchWrapper);
if (CollectionUtils.isNotEmpty(nodes)) {
// 查询相关祖先节点
Set<Long> parentIds = new HashSet<>();
nodes.forEach(node -> {
Set<Long> hierarchy = TreeUtils.longParents(node.getHierarchy());
parentIds.addAll(hierarchy);
});
// id
Wrapper<Food> ancestorWrapper = Condition.wrapper();
ancestorWrapper.in(Food.ID, parentIds);
list = this.selectList(ancestorWrapper);
}
} else {
list = this.selectList(null);
}
// 列表转树
return list2map(list);
}
/**
* 列表 转 树
*
* @param itemCategories 故障描述
* @return 树
*/
private List<FoodTreeVo> list2map(List<Food> itemCategories) {
if (itemCategories == null) {
return null;
}
Map<Long, FoodTreeVo> map = itemCategories.stream().collect(Collectors.toMap(Food::getId, Food -> {
FoodTreeVo treeVO = FoodTreeVo.bean2VO(Food);
treeVO.setChildren(new ArrayList<>());
return treeVO;
}));
return map.entrySet().parallelStream()
.peek(entry -> {
Long parentId = entry.getValue().getParentId();
FoodTreeVo treeVO = map.get(parentId);
if (treeVO != null) {
treeVO.getChildren().add(entry.getValue());
}
})
.map(Map.Entry::getValue)
.filter(menu -> TreeUtils.ROOT.equals(menu.getParentId()))
.sorted(Comparator.comparing(FoodTreeVo::getSort))
.collect(Collectors.toList());
}
二、前端递归处理 table组件关键字冲突
代码如下(示例):
TransfromResult(resultArr) {
let self = this;
function ResetMenu(itemArr, level = 1) {
itemArr.forEach((item, index) => {
//判断如果为空话就删除点数组里面的空对象
if (!item) {
itemArr.splice(index, 1);
return;
}
item.has_children = item.hasChildren;
if (item.children && item.children.length) {
ResetMenu(item.children);
}
delete item.hasChildren;
});
}
ResetMenu(resultArr);
return resultArr;
},