树形结构过滤,保留父节点-filterTreeData

1.使用函数

//树形结构筛选,过滤保留父节点
export function filterTree(
  node: any[], //树形结构
  callBack = (node: any): boolean => {
	return true;
  }, //子节点过滤方式,如果返回为true则匹配成功,如果返回为false则匹配失败,
  option: {
	childrenKey?: string; //子节点key 默认为children
	isFilterBranchNode?: boolean; //分支节点是否需要参与过滤
  } = {}
) {
  if (!isArray(node)) return;
  node = cloneDeep(node);
  return _filterTree(node, callBack, option);
}
//内部函数
function _filterTree(
  node: any[],
  callBack = (node: any): boolean => {
	return true;
  },
  option: {
	childrenKey?: string; //子节点key 默认为children
	isFilterBranchNode?: boolean; //是否过滤分支节点 默认为ture
  } = {}
) {
  if (!node?.length) {
	return [];
  }
  const { childrenKey = 'children', isFilterBranchNode = true } = option;
  const newNode: any[] = [];
  for (let i = 0, l = node.length; i < l; i++) {
	const item = node[i];
	if (item?.[childrenKey]?.length) {
	  const newChildrenNode: any[] = _filterTree(item.children, callBack, option);
	  if (newChildrenNode?.length) {
		item[childrenKey] = newChildrenNode;
		newNode.push(item);
	  } else {
		delete item[childrenKey];
		if (isFilterBranchNode && callBack(item)) {
		  newNode.push(item);
		}
	  }
	} else {
	  if (callBack(item)) {
		newNode.push(item);
	  }
	}
  }
  return newNode;
}

2.如何使用

 useTreeData -> 使用数组
 treeData -> 接口拿回的数据
 
<a-input-search
    v-model:value="searchValue"
    allowClear
    style="margin-bottom: 8px"
    placeholder="搜索"
    enter-button
    @search="handelTreeSearch"
  >
    <template #prefix><SearchOutlined /></template>
</a-input-search>

const handelTreeSearch = (val: string) => {
  if (!val) {
    this.useTreeData = this.treeData;
    return;
  }
  this.useTreeData = filterTree(
    this.treeData,
    (node: any[]) => {
      return node?.name?.indexOf(val) != -1;
    },
    { isFilterBranchNode: true }
  );
}
posted @ 2024-01-18 09:48  SKa-M  阅读(325)  评论(0编辑  收藏  举报