Data structures retrieved from the back end

When code is main, perentId is the id of another node, and parentId is the child node

   const arrs = [
              {
                id: 1.parentId: "".name: "111".hasChildren: 2.code: "main"
              },
              {
                id: 2.parentId: 1.name: "222".hasChildren: 1.code: "aaa"
              },
              {
                id: 3.parentId: 2.name: "333".hasChildren: 1.code: "bbb"
              },
              {
                id: 4.parentId: 1.name: "444".hasChildren: 0.code: "ccc"
              },
              {
                id: 5.parentId: 3.name: "555".hasChildren: 0.code: "ddd"}];Copy the code

Ii. The tree structure is as follows:

Ii. Code implementation is as follows:

<template> <div> <el-tree class="_tree" :data="treeList" :props="defaultProps" node-key="id" :highlight-current="true" ref="category" > <span slot-scope="{ node, data }"> <i :class="data.icon ? data.icon : 'el-icon-fa-folder'"></i> <span class="tree_label">{{ node.label }}</span> </span> </el-tree> </div> </template> <script> export default { data() { return { defaultProps: { children: "children", label: "label" }, treeList: [] }; }, mounted() { this.getComnTree(this.treeInfo); }, methods: {getComnTree() {// code is main, perentId is another id, parentId is the child, arrs = [{id:) const arrs = [{id:) const arrs = [{id:) 1, parentId: "", name: "111", hasChildren: 2, code: "main", icon: "" }, { id: 2, parentId: 1, name: "222", hasChildren: 1, code: "aaa", icon: "el-icon-date" }, { id: 3, parentId: 2, name: "333", hasChildren: 1, code: "bbb", icon: "" }, { id: 4, parentId: 1, name: "444", hasChildren: 0, code: "ccc", icon: "" }, { id: 5, parentId: 3, name: "555", hasChildren: 0, code: "ddd", icon: "" } ]; this.treeList = this.formTheTree(arrs); }, formTheTree(records) { var result = []; records.forEach(val => { if (val.code === "main") { let parent = { label: val.name, id: val.id, icon: val.icon }; if (val.hasChildren) { this.$set(parent, "children", this.getChilds(val.id, records)); } result.push(parent); }}); return result; }, getChilds(id, array) { let childs = []; array.forEach(val => { if (id === val.parentId) { childs.push({ id: val.id, label: val.name, icon: val.icon }); }}); childs.forEach(childNode => { let currNode = this.getChilds(childNode.id, array); if (currNode.length > 0) { childNode.children = currNode; }}); return childs; }}}; </script> <style lang="scss"> ._tree { color: #444; padding-left: 15px; span { color: $icon_color; } i { margin-right: 6px; } .tree_label { font-size: 14px; color: #333; }} /* Rewrite the Tree component icon style */. El-icon-fa-folder :before {content: "\F07B"; color: #008ecd; } </style>Copy the code

The tree menu looks like this:

Reference: blogs