class CategoryUtil { #tree = [] constructor (tree) { this.#tree = tree this.#fillParent(this.#tree) } /** * 获取面包屑 * * @param uid * @returns {*[]} */ getBreadcrumb (uid) { let target = this.#getNode(this.#tree, uid) if (target == null) { return [] } const nodes = [] while (target != null) { nodes.push(target) target = target.parent } return nodes.map(node => { return { uid: node.uid, title: node.title, uri: node.uri } }).reverse() } /** * 获取栏目 * * @param uid * @returns {*|null} */ getCategory (uid) { return this.#getNode(this.#tree, uid) } /** * 获取目标节点 * * @param categoryList 栏目列表 * @param uid 栏目唯一标识 * @returns {*|null} */ #getNode (categoryList, uid) { for (const node of categoryList) { if (node.uid === uid) { return node } if (node.children != null && node.children.length > 0) { const result = this.#getNode(node.children, uid) if (result != null) { return result } } } return null } /** * 填充父节点 * * @param categoryList 栏目列表 * @param parent 父节点 */ #fillParent (categoryList, parent) { for (const node of categoryList) { node.parent = parent if (node.children != null && node.children.length > 0) { this.#fillParent(node.children, node) } } } } export default CategoryUtil