需要lodash
//data 需要过滤的数据 keyword搜索关键字
//data 中要有title 和 key 属性 title就是展示值和keyword匹配的值
import {treeFilter} from '@/lib/TreeFilter'
let newData= treeFilter(data,keyword)
// 过滤函数
function _filterFn(data, filterText) {
return !filterText || data.title.indexOf(filterText) > -1;
}
function _checkedFn(node, checkedList) {
return checkedList && checkedList.indexOf(node.key) > -1
}
function _treeFilter(nodes, filterText, checkedList) {
if (!(nodes && nodes.length)) {
return;
}
const newChildren = [];
// eslint-disable-next-line no-restricted-syntax
for (const node of nodes) {
if (_filterFn(node, filterText) || _checkedFn(node, checkedList)) {
const _node = {...node};
// _node.children = _treeFilter(_node.children, filterText);
newChildren.splice(newChildren.length, 0, _node);
} else {
const children = _treeFilter(node.children, filterText, checkedList);
if (children && children.length) {
const _node = {...node};
_node.children = children;
newChildren.splice(newChildren.length, 0, _node);
}
}
}
return newChildren;
}
export function treeFilter(nodes, filterText, checkedList) {
if (!filterText) {
return nodes
}
if (checkedList && checkedList.length && _.isObject(checkedList[0])) {
checkedList = _.map(checkedList, node => node.key);
}
return _treeFilter(nodes, filterText, checkedList);
}