需要lodash

    1. //data 需要过滤的数据 keyword搜索关键字
    2. //data 中要有title 和 key 属性 title就是展示值和keyword匹配的值
    3. import {treeFilter} from '@/lib/TreeFilter'
    4. let newData= treeFilter(data,keyword)
    1. // 过滤函数
    2. function _filterFn(data, filterText) {
    3. return !filterText || data.title.indexOf(filterText) > -1;
    4. }
    5. function _checkedFn(node, checkedList) {
    6. return checkedList && checkedList.indexOf(node.key) > -1
    7. }
    8. function _treeFilter(nodes, filterText, checkedList) {
    9. if (!(nodes && nodes.length)) {
    10. return;
    11. }
    12. const newChildren = [];
    13. // eslint-disable-next-line no-restricted-syntax
    14. for (const node of nodes) {
    15. if (_filterFn(node, filterText) || _checkedFn(node, checkedList)) {
    16. const _node = {...node};
    17. // _node.children = _treeFilter(_node.children, filterText);
    18. newChildren.splice(newChildren.length, 0, _node);
    19. } else {
    20. const children = _treeFilter(node.children, filterText, checkedList);
    21. if (children && children.length) {
    22. const _node = {...node};
    23. _node.children = children;
    24. newChildren.splice(newChildren.length, 0, _node);
    25. }
    26. }
    27. }
    28. return newChildren;
    29. }
    30. export function treeFilter(nodes, filterText, checkedList) {
    31. if (!filterText) {
    32. return nodes
    33. }
    34. if (checkedList && checkedList.length && _.isObject(checkedList[0])) {
    35. checkedList = _.map(checkedList, node => node.key);
    36. }
    37. return _treeFilter(nodes, filterText, checkedList);
    38. }