Java后端 || ElementUI 显示后端树形表格数据
在Java后端处理树形结构的数据并返回给ElementUI的前端,你可以使用一个递归方法来构建树形结构。以下是一个简单的示例:
Java后端代码(使用Spring Boot):
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
@RestController
public class TreeController {
@GetMapping("/tree-data")
public List<TreeNode> getTreeData() {
// 模拟数据库查询
List<TreeNode> nodes = new ArrayList<>();
// ... 查询数据库并填充nodes
return buildTree(nodes);
}
private List<TreeNode> buildTree(List<TreeNode> nodes) {
List<TreeNode> tree = new ArrayList<>();
for (TreeNode node : nodes) {
if (node.getParentId() == null) {
// 找到根节点
TreeNode root = new TreeNode(node.getId(), node.getName(), null);
root.setChildren(buildChildNodes(node.getId(), nodes));
tree.add(root);
}
}
return tree;
}
private List<TreeNode> buildChildNodes(Integer parentId, List<TreeNode> nodes) {
List<TreeNode> children = new ArrayList<>();
for (TreeNode node : nodes) {
if (parentId.equals(node.getParentId())) {
TreeNode child = new TreeNode(node.getId(), node.getName(), parentId);
child.setChildren(buildChildNodes(node.getId(), nodes));
children.add(child);
}
}
return children;
}
static class TreeNode {
private Integer id;
private String name;
private Integer parentId;
private List<TreeNode> children;
public TreeNode(Integer id, String name, Integer parentId) {
this.id = id;
this.name = name;
this.parentId = parentId;
}
// Getters and Setters
// ...
}
}
ElementUI前端代码(Vue.js):
<template>
<el-tree :data="treeData" :props="defaultProps"></el-tree>
</template>
<script>
export default {
data() {
return {
treeData: [],
defaultProps: {
children: 'children',
label: 'name'
}
};
},
created() {
this.fetchTreeData();
},
methods: {
fetchTreeData() {
// 假设已经配置了axios
axios.get('/tree-data')
.then(response => {
this.treeData = response.data;
})
.catch(error => {
评论已关闭