需求:实现TreeView按节点Title与Description过滤并展示父级层级
Let's break down how to fix your TreeView filtering issue. The core problem with your current code is that it only checks the current item's title and doesn't account for nested child matches or the description field. We need a recursive approach to check both the node itself and all its descendants, plus ensure parent nodes stay visible if any of their children match the query.
Original TreeView Structure
First, let's visualize your existing tree for clarity:
- Item 1 (id:132)
- Item 1.1 (id:133)
- Item 1.1.1 (id:134)
- Item 1.1 (id:133)
- Item 2 (id:135)
- Item 3 (id:136)
- Item 3.1 (id:137)
Step 1: Create a Recursive Match Checker
We'll build a helper function that recursively checks if a node (or any of its children) matches the query against either title or description:
// Helper function to check if a node or its descendants match the query function hasMatchingDescendant(item, query) { // Check current node's title and description const currentNodeMatches = item.title.includes(query) || item.description.includes(query); // Recursively check all child nodes const childNodeMatches = item.nodes.some(child => hasMatchingDescendant(child, query)); // Return true if either the current node or any child matches return currentNodeMatches || childNodeMatches; }
Step 2: Update the Visibility Function
Now modify your visible function to use this helper. It will show all nodes when there's no query, and only show nodes that either match themselves or have matching descendants when a query exists:
this.visible = function(item) { // If no query exists, show everything if (!this.query || this.query.length === 0) { return true; } // Check if this node or any of its children match the query return hasMatchingDescendant(item, this.query); };
How This Works
- When you search for a term that matches
Item 1.1.1, the helper function will returntrueforItem 1.1.1, then propagate up:Item 1.1will returntrue(because its child matches), andItem 1will also returntrue(because its child matches). This keeps the full hierarchy intact. - The function checks both
titleanddescription, so matches in either field will trigger visibility. - If a node has no matching descendants and doesn't match itself, it will be hidden.
Edge Case Notes
- Empty
descriptionfields won't cause false matches becauseincludes(query)will only return true if the query is present (and your code already checks thatquery.length > 0). - This works for any depth of nested nodes, not just one level of parent-child.
内容的提问来源于stack exchange,提问作者Andre Leoni

