// 树节点中查询遍历组织 getNode(data, key, val) { let treeNode = ""; data.some(item => { let flag = false; console.log("item[" + key + "]", item[key], "val", val); if (item[key] === val) { treeNode = item; flag = true; } else if (item.children && item.children.length) { treeNode = this.getNode(item.children, key, val); if (treeNode) flag = true; } return flag; }); return treeNode; }, changeCurrentNode(id) { var id = this.$isEmpty(id) ? "" : id; this.$nextTick(() => { this.$refs.tree.setCurrentKey(this.$isEmpty(id) ? null : id); }); this.currentNodeKey = id; this.$nextTick(() => { const node = this.$refs.tree.getNode(this.currentNodeKey); console.log("node--->", node); this.handleNodeClick(node.data); this.scrollToTreeCurrent(node); }); }, // 定位到tree选择位置 scrollToTreeCurrent(parentNode) { if (!parentNode) return false; let level = -1; let dom = document.querySelector(".brand-tree"); // 获取 tree外层的dom let nodeCount = 0; // tree中展开节点总数 let nodeIndex = 0; // tree中选中节点 // 获取tree节点高度 let nodeHeight = 30; // 通过选中节点 获取顶层父节点 并展开 while (level != 0) { this.$refs.tree.store.nodesMap[ parentNode.data[this.nodeKey] ].expanded = true; parentNode = parentNode.parent; level = parentNode.level; } this.$nextTick(() => { const getNodeCount = function(val) { val.childNodes.forEach(e => { nodeCount++; if (e.isCurrent) { nodeIndex = nodeCount; } if (e.expanded) { getNodeCount(e); } }); }; getNodeCount(parentNode); // 获取展开节点总数和高亮节点位置 // 计算 选中节点位置 并通过scrollTo方法定位 let height = Number( window.getComputedStyle(dom).height.replace("px", "") ); // 计算位置大约在tree中间 let scroll = Math.max(nodeIndex * nodeHeight - 0.4 * height, 0); console.log("scroll--->", window.getComputedStyle(dom).height); setTimeout(() => { dom.scrollTo(0, scroll); }, 300); }); }, //数组转为组织树 arrToTree(_data) { let data = this.$deepClone(_data); let result = []; if (!Array.isArray(data)) { return result; } data.forEach(item => { delete item.children; }); let map = {}; data.forEach((item, index) => { item.index = index; map[item.id] = item; }); data.forEach(item => { let parent = map[item.pId]; if (parent) { (parent.children || (parent.children = null)).push(item); } else { result.push(item); } }); return this.arrayTreeAddLevel(result); }, // 给组织树添加level标识 arrayTreeAddLevel(array, levelName = "level", childrenName = "children") { if (!Array.isArray(array)) return []; const recursive = ( array, level = -1, name = "", nameSecond = this.nameSecond ) => { level++; return array.map(v => { v[levelName] = level; v[nameSecond] = name == "" ? v.name : name + "-" + v.name; const child = v[childrenName]; if (child && child.length) recursive(child, level, v[nameSecond], nameSecond); return v; }); }; return recursive(array); },
标签:vue,return,level,组织,tree,item,let,数组,data From: https://www.cnblogs.com/charlie098765/p/16954608.html