一、对于vue来说,树形成的元素主要是label和children.
二、后台形成树结构代码
public ResponseData selectListCustom(Map<String, Object> map) { try{ // 构建条件 QueryWrapper<ScheDeptInfo> wrapper = new QueryWrapper<>(); wrapper.orderByAsc("parent_code"); // 查询所有的排班组织信息 List<ScheDeptInfo> deptInfoList = scheDeptInfoMapper.selectList(wrapper); List<TreeNodeInfo> treeList = new ArrayList<>(); for(ScheDeptInfo info : deptInfoList) { if (info.getParentCode().equals("0")) { TreeNodeInfo treeNodeInfo = new TreeNodeInfo(); treeNodeInfo.setPid(0L); treeNodeInfo.setId(info.getId()); treeNodeInfo.setDeptCode(info.getDeptCode()); treeNodeInfo.setLabel(info.getDeptName()); treeList.add(treeNodeInfo); } else { getLevelData(treeList, info); } } return ResponseUtil.success(treeList); }catch (Exception e){ return globalExceptionHandler.exceptionGet(e); } }
三、递归形成需要的数据
private void getLevelData( List<TreeNodeInfo> treeList ,ScheDeptInfo info){ for(int i = 0; i < treeList.size(); i++){ TreeNodeInfo node = treeList.get(i); if(node.getChildren() == null){ node.setChildren(new ArrayList<>()); } if(info.getParentCode().equals(node.getDeptCode())){ TreeNodeInfo treeNodeInfo = new TreeNodeInfo(); treeNodeInfo.setPid(info.getParentId()); treeNodeInfo.setId(info.getId()); treeNodeInfo.setDeptCode(info.getDeptCode()); treeNodeInfo.setLabel(info.getDeptName()); node.getChildren().add(treeNodeInfo); }else if(node.getChildren().size() > 0){ getLevelData(node.getChildren(), info); } } }
四、返回前端的实体
@Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) @ApiModel(value="TreeNodeInfo", description="树结构") public class TreeNodeInfo implements Serializable { private static final long serialVersionUID = 1L; private String label; private List<TreeNodeInfo> children; // 唯一标识 private Long id; // 父节点 private Long pid; private String deptCode; }
五、前端形成组织树
<template> <div class="tree"> <el-input v-model="treefilter" class="treeinput" placeholder="输入关键字进行搜索"> <i slot="prefix" class="el-input__icon el-icon-search" /> </el-input> <el-tree ref="tree" class="treestyle" node-key="id" :data="contTree" :filter-node-method="filterNode" default-expand-all @node-click="treeNodeClick" /> </div> </template> <script> /* eslint-disable */ import { selectOrgList } from "@/api/common" export default { data() { return { treefilter: "", defaultProps: { children: "children", label: "label", }, contTree: [], }; }, watch: { treefilter(val) { this.$refs.tree.filter(val); }, }, mounted() { this.getDataTreeList(); }, methods: { // 查询排版系统中所有的组织信息,后续加过滤 getDataTreeList(){ let params = new FormData(); selectOrgList(params).then(res => { if (res.code == 200) { let tree = res.data this.contTree = tree } else { this.$publicmethod.showMessage(res.message, this.$publicmethod.ErrorType) } }); }, treeNodeClick(data) { this.$emit("treeNodeClick", data); }, filterNode(value, data) { if (!value) return true; return data.label.indexOf(value) !== -1; }, }, }; </script>