// 加载树形数据
const load = async () => {
try {
const res = await request.get(‘/category/tree’)
if (res.data.code === 200) {
tableData.value = res.data
} else {
ElMessage.error(‘数据加载失败’)
}
} catch (error) {
ElMessage.error(‘请求失败,请检查网络’)
}
}F12键检查发现{code: "200", msg: "请求成功",…}
code
:
"200"
data
:
[{id: 1, title: "前端开发", parentId: null, sort: 0,…}, {id: 2, title: "后端开放", parentId: null, sort: 0,…},…]
0
:
{id: 1, title: "前端开发", parentId: null, sort: 0,…}
children
:
[{id: 4, title: "Vue", parentId: 1, sort: 1, children: null},…]
0
:
{id: 4, title: "Vue", parentId: 1, sort: 1, children: null}
children
:
null
id
:
4
parentId
:
1
sort
:
1
title
:
"Vue"
1
:
{id: 5, title: "JavaScript", parentId: 1, sort: 1, children: null}
children
:
null
id
:
5
parentId
:
1
sort
:
1
title
:
"JavaScript"
2
:
{id: 6, title: "JQuery", parentId: 1, sort: 1, children: null}
children
:
null
id
:
6
parentId
:
1
sort
:
1
title
:
"JQuery"
id
:
1
parentId
:
null
sort
:
0
title
:
"前端开发"
1
:
{id: 2, title: "后端开放", parentId: null, sort: 0,…}
children
:
[{id: 7, title: "Java", parentId: 2, sort: 2, children: null},…]
0
:
{id: 7, title: "Java", parentId: 2, sort: 2, children: null}
children
:
null
id
:
7
parentId
:
2
sort
:
2
title
:
"Java"
1
:
{id: 8, title: "C++", parentId: 2, sort: 2, children: null}
children
:
null
id
:
8
parentId
:
2
sort
:
2
title
:
"C++"
2
:
{id: 9, title: "Python", parentId: 2, sort: 2, children: null}
children
:
null
id
:
9
parentId
:
2
sort
:
2
title
:
"Python"
id
:
2
parentId
:
null
sort
:
0
title
:
"后端开放"
2
:
{id: 3, title: "数据库", parentId: null, sort: 0,…}
children
:
[{id: 10, title: "MySQL", parentId: 3, sort: 3, children: null}]
id
:
3
parentId
:
null
sort
:
0
title
:
"数据库"
msg
:
"请求成功"但是出现数据加载失败,而且页面也没有展示数据.已经知道后端 @GetMapping("/tree")
public Result getCategoryTree() {
List<Category> treeData = categoryService.getCategoryTree();
return Result.success( treeData);
}public List<Category> getCategoryTree() {
List<Category> allCategories = categoryMapper.selectAll();
Map<Integer, Integer> idIndexMap = new HashMap<>();
// 建立ID到列表索引的映射
for (int i = 0; i < allCategories.size(); i++) {
idIndexMap.put(allCategories.get(i).getId(), i);
}
// 构建树形结构
for (Category node : allCategories) {
if (node.getParentId() != null) {
Integer parentIndex = idIndexMap.get(node.getParentId());
if (parentIndex != null) {
Category parent = allCategories.get(parentIndex);
if (parent.getChildren() == null) {
parent.setChildren(new ArrayList<>());
}
parent.getChildren().add(node);
}
}
}
// 过滤出根节点
return allCategories.stream()
.filter(c -> c.getParentId() == null)
.sorted(Comparator.comparingInt(Category::getSort))
.collect(Collectors.toList());
}
怎么成功展示数据
最新发布