浏览代码

feat(tree): new Tree 时可以指定默认的展开收起状态

zhangweicheng 4 年之前
父节点
当前提交
567cbadb82
共有 2 个文件被更改,包括 6 次插入5 次删除
  1. 2 1
      tree/src/nodeCtx.ts
  2. 4 4
      tree/src/tree.ts

+ 2 - 1
tree/src/nodeCtx.ts

@@ -9,9 +9,10 @@ export class NodeContext<T = any> {
   // 展开收起
   expanded = false;
 
-  constructor(node: TreeNode & T, tree: Tree) {
+  constructor(node: TreeNode & T, tree: Tree, expanded?: boolean) {
     this.ref = node;
     this.tree = tree;
+    if (expanded) this.expanded = expanded;
   }
 
   ID(): string {

+ 4 - 4
tree/src/tree.ts

@@ -61,7 +61,7 @@ export class Tree<T = any> {
   // 节点上下文与节点ID映射
   ctxMap: CtxIDMap<T>;
 
-  constructor(rawData: TreeRaw[], rootID = '-1') {
+  constructor(rawData: TreeRaw[], rootID = '-1', expanded?: boolean) {
     this.rootID = rootID;
     this.rawData = this.genNodeContext(rawData);
     this.rawData = Tree.sort(this.rawData);
@@ -69,7 +69,7 @@ export class Tree<T = any> {
     this.IDMap = {};
     this.parentMap = {};
     this.ctxMap = {};
-    this.genMap(this.rawData);
+    this.genMap(this.rawData, expanded);
     this.genData();
   }
 
@@ -94,10 +94,10 @@ export class Tree<T = any> {
   }
 
   // 生成映射表
-  private genMap(data: (TreeNode & T)[]): void {
+  private genMap(data: (TreeNode & T)[], expanded?: boolean): void {
     data.forEach(item => {
       this.IDMap[item.ID] = item;
-      this.ctxMap[item.ID] = new NodeContext(item, this);
+      this.ctxMap[item.ID] = new NodeContext(item, this, expanded);
       (
         this.parentMap[item.parentID] || (this.parentMap[item.parentID] = [])
       ).push(item);