import { EmopTreeDataType } from "./EmopTreeDataType"; import { NzTreeNode, NzTreeNodeOptions } from "ng-zorro-antd/tree"; export class EmopTree { checkable?: boolean = false; async?: boolean = false; data?: NzTreeNodeOptions[]; expandedKeys?: string[] = []; contextMenu?; ref; constructor( protected tempData: EmopTreeDataType, ) { for (const key in this.tempData) { this[key] = this.tempData[key] || this[key]; } } /** * 展开到指定位置(支持异步) * @param seq 传入的seq值,例如"1600-1700",则会按照顺序依次展开 * @param callback 获取数据的异步函数 * - data 当前需要被展开的节点数据 * - next 调用next()则进行下一步 * @param options 配置项内容 * - index keys的当前索引值 * */ async expand(seq: string | string[], callback?: Function, options?) { let keys = seq; if (typeof seq === 'string') { keys = seq.split('-'); } // 默认值 if (!options) options = { index: 0 }; if (keys.length !== options.index) { // 要展开的目标节点 const target = this.getTreeDataByKey(keys[options.index]); if (target) { ++options.index; if (keys.length !== options.index) target.expanded = true; this.expand(keys, callback, options); } else { await new Promise((resolve) => { callback(this.getTreeDataByKey(keys[options.index - 1]), resolve); }); if (!this.getTreeDataByKey(keys[options.index])) return console.error(`找不到key值为${keys[options.index]}的节点`); setTimeout(() => { this.expand(keys, callback, options); }, 0); } } this.refreshData(); } /** * 刷新数据 */ refreshData() { this.data = [...this.data]; } /** * 根据key值获取指定节点数据 * @param key * @returns */ getTreeDataByKey(key: string) { const target = this.getTreeNodeByKey(key)?.origin; if (target) { return target; } } /** * 根据key值获取指定节点 * @param key * @returns */ getTreeNodeByKey(key: string): NzTreeNode { if (this.ref) { return this.ref.getTreeNodeByKey(key); } else { console.error('找不到ref节点'); } } selectedNodeByKey(key: string, options?: { click: boolean; }) { const targetData = this.getTreeDataByKey(key); if (targetData) { targetData.selected = true; this.refreshData(); if (options.click) this.ref.nzClick.emit({ ...targetData, node: this.getTreeNodeByKey(key), isFn: true }); } else { console.error(`找不到key值为${key}的节点`); } } /** * 根据key值添加子节点(从服务器中加载子节点数据请使用updateChildrenByKey) * @param key * @param children 子节点数据 * @param index 插入的索引位置 */ addChildrenByKey(key: string, children: any[], index?: number) { const targetNode = this.getTreeNodeByKey(key); if (targetNode) { children.forEach(item => item.seq = targetNode.origin.seq + '-' + item.key); targetNode.addChildren(children, index); this.refreshData(); } else { console.error(`找不到key值为${key}的节点`); } } /** * 根据key值更新子节点(从服务器中加载子节点数据请使用该函数) * @param key * @param children */ updateChildrenByKey(key: string, children: any[]) { const targetNode = this.getTreeNodeByKey(key); children.forEach(item => item.seq = targetNode.origin.seq + '-' + item.key); if (!targetNode) return console.error(`找不到key值为${key}的节点`); if (targetNode && !targetNode.origin.children.length) { targetNode.addChildren(children); this.refreshData(); } } }