Browse Source

fix(cascader): bug [#1233] (#1239)

dongj0316 3 years ago
parent
commit
21289244ba

+ 0 - 24
src/packages/__VUE/cascader/__tests__/cascader.spec.ts

@@ -193,30 +193,6 @@ describe('Tree', () => {
 
   const tree = new Tree(mockOptions);
 
-  test('getNodeByValue', () => {
-    const node = tree.getNodeByValue('西湖区');
-    expect(node).toBeTruthy();
-    expect(node).toMatchObject({ text: '西湖区', value: '西湖区' });
-  });
-
-  test('getPathNodesByNode', () => {
-    const node = tree.getNodeByValue('西湖区') as CascaderOption;
-    expect(node).toBeTruthy();
-    expect(node.value).toBe('西湖区');
-
-    const pathNodes = tree.getPathNodesByNode(node as CascaderOption);
-    const mappedPathNodes = pathNodes.map(({ text, value }) => ({
-      text,
-      value
-    }));
-
-    expect(mappedPathNodes).toMatchObject([
-      { text: '浙江', value: '浙江' },
-      { text: '杭州', value: '杭州' },
-      { text: '西湖区', value: '西湖区' }
-    ]);
-  });
-
   test('getPathNodesByValue', () => {
     const pathNodes = tree.getPathNodesByValue(['杭州', '杭州', '西湖区']);
     const mappedPathNodes = pathNodes.map(({ text, value }) => ({

+ 14 - 17
src/packages/__VUE/cascader/tree.ts

@@ -23,6 +23,7 @@ class Tree {
     }
   }
 
+  // for test
   getNodeByValue(value: CascaderOption['value']): CascaderOption | void {
     let foundNode;
     eachTree(this.nodes, (node: CascaderOption) => {
@@ -35,30 +36,26 @@ class Tree {
     return foundNode;
   }
 
-  getPathNodesByNode(node: CascaderOption): CascaderOption[] {
-    const nodes = [];
-
-    while (node) {
-      nodes.unshift(node);
-      node = node._parent;
-    }
-
-    return nodes;
-  }
-
   getPathNodesByValue(value: CascaderValue): CascaderOption[] {
-    if (Array.isArray(value) && !value.length) {
+    if (!value.length) {
       return [];
     }
 
-    const tail = Array.isArray(value) ? value[value.length - 1] : value;
+    const pathNodes = [];
+    let currentNodes: CascaderOption[] | void = this.nodes;
 
-    const node = this.getNodeByValue(tail);
-    if (!node) {
-      return [];
+    while (currentNodes && currentNodes.length) {
+      const foundNode: CascaderOption | void = currentNodes.find((node) => node.value === value[node.level as number]);
+
+      if (!foundNode) {
+        break;
+      }
+
+      pathNodes.push(foundNode);
+      currentNodes = foundNode.children;
     }
 
-    return this.getPathNodesByNode(node);
+    return pathNodes;
   }
 
   isLeaf(node: CascaderOption, lazy: boolean): boolean {