目录

前端实现树形表格搜索功能

目录

前端实现树形表格搜索功能

https://img-home.csdnimg.cn/images/20240711112329.png

// 搜索
const handleSearch = () => {
  if (form.category_name) {
    tableData = rebuildData(form.category_name, tableData)
  
  }
}
// 重点代码 根据name字段模糊匹配树状结构数据,最后将处理好的数据返回出来
const rebuildData = (value: any, arr: any) => {
  if (!arr) {
    return []
  }
  let newArr: any = []
  arr.forEach((element: any) => {
    console.log(element, 'element')
    // indexOf用来判读当前节点name字段是否包含所搜索的字符串value
    // 返回值:包含则返回索引值,反之返回-1
    if (element.category_name.indexOf(value) > -1) {
      const ab = rebuildData(value, element.children)
      const obj = {
        ...element,
        children: ab
      }
      newArr.push(obj)
    } else {
      // 判断当前节点知否有子节点,并且子节点中有数据,有数据继续递归查找
      if (element.children && element.children.length > 0) {
        const ab = rebuildData(value, element.children)
        const obj = {
          ...element,
          children: ab
        }
        if (ab && ab.length > 0) {
          newArr.push(obj)
        }
      }
    }
  })
  return newArr
}