Browse Source

feat(tree): 1. 添加自定义数据过滤判断方法 2. 添加搜索完成自动展开结果选项 3. 添加搜索完成自动选中结果选项 4. 树节点数据变化时强制搜索(同步searchData避免展示错误) (#1132)

Lan 3 years ago
parent
commit
e00578c40a
2 changed files with 38 additions and 3 deletions
  1. 19 2
      src/components/Tree/src/Tree.vue
  2. 19 1
      src/components/Tree/src/props.ts

+ 19 - 2
src/components/Tree/src/Tree.vue

@@ -211,16 +211,32 @@
           searchState.startSearch = false;
           return;
         }
+        const { filterFn, checkable, expandOnSearch, checkOnSearch } = unref(props);
         searchState.startSearch = true;
-        const { title: titleField } = unref(getReplaceFields);
+        const { title: titleField, key: keyField } = unref(getReplaceFields);
 
+        const searchKeys: string[] = [];
         searchState.searchData = filter(
           unref(treeDataRef),
           (node) => {
-            return node[titleField]?.includes(searchValue) ?? false;
+            const result = filterFn
+              ? filterFn(searchValue, node, unref(getReplaceFields))
+              : node[titleField]?.includes(searchValue) ?? false;
+            if (result) {
+              searchKeys.push(node[keyField]);
+            }
+            return result;
           },
           unref(getReplaceFields),
         );
+
+        if (expandOnSearch && searchKeys.length > 0) {
+          setExpandedKeys(searchKeys);
+        }
+
+        if (checkOnSearch && checkable && searchKeys.length > 0) {
+          setCheckedKeys(searchKeys);
+        }
       }
 
       function handleClickNode(key: string, children: TreeItem[]) {
@@ -239,6 +255,7 @@
 
       watchEffect(() => {
         treeDataRef.value = props.treeData as TreeItem[];
+        handleSearch(unref(searchText));
       });
 
       onMounted(() => {

+ 19 - 1
src/components/Tree/src/props.ts

@@ -1,5 +1,12 @@
 import type { PropType } from 'vue';
-import type { ReplaceFields, ActionItem, Keys, CheckKeys, ContextMenuOptions } from './typing';
+import type {
+  ReplaceFields,
+  ActionItem,
+  Keys,
+  CheckKeys,
+  ContextMenuOptions,
+  TreeItem,
+} from './typing';
 import type { ContextMenuItem } from '/@/hooks/web/useContextMenu';
 import type { TreeDataItem } from 'ant-design-vue/es/tree/Tree';
 import { propTypes } from '/@/utils/propTypes';
@@ -66,6 +73,17 @@ export const basicProps = {
   rightMenuList: {
     type: Array as PropType<ContextMenuItem[]>,
   },
+  // 自定义数据过滤判断方法(注: 不是整个过滤方法,而是内置过滤的判断方法,用于增强原本仅能通过title进行过滤的方式)
+  filterFn: {
+    type: Function as PropType<
+      (searchValue: any, node: TreeItem, replaceFields: ReplaceFields) => boolean
+    >,
+    default: null,
+  },
+  // 搜索完成时自动展开结果
+  expandOnSearch: propTypes.bool.def(false),
+  // 搜索完成自动选中所有结果,当且仅当 checkable===true 时生效
+  checkOnSearch: propTypes.bool.def(false),
 };
 
 export const treeNodeProps = {