如何使用ag-grid CustomFilterComponent构建自定义lookup搜索筛选功能
基于ag-grid CustomFilterComponent 实现自定义Lookup搜索
前置数据结构规范
首先要把原始提供的映射数组调整为符合JS语法的合法结构,因为原始的tokens写法缺失数组结构,无法直接遍历匹配:
// 规范后的Lookup映射数据 const lookupMapping = [ { key: 'michael', value: 'michael', tokens: ['michael', 'mich', 'ael', '+0912312321'] }, { key: 'natalie', value: 'natalie', tokens: ['natalie', 'lie', '+091212'] } ]
匹配规则完全贴合需求:只要用户输入的内容是任意token的子串,即可命中对应条目关联的表格行,不管输入的是全名、姓名片段还是关联手机号。
自定义筛选组件核心实现
按照ag-grid CustomFilterComponent的强制接口要求编写可复用的筛选组件,核心是把默认的单元格值直接匹配逻辑,替换为「token集合遍历匹配→生成命中白名单→校验当前行单元格值是否在白名单内」的流程:
class LookupFilter { agGridParams = null currentInputValue = '' attachedLookupList = [] // 组件初始化,接收ag-grid传入的列参数 init(params) { this.agGridParams = params // 从列配置中读取当前列关联的lookup映射,支持不同列配置不同规则 this.attachedLookupList = params.filterParams?.lookupMapping || [] // 构造筛选面板的DOM this.rootDom = document.createElement('div') this.rootDom.style.padding = '10px' this.searchInput = document.createElement('input') this.searchInput.placeholder = '输入名称、片段或手机号搜索' this.searchInput.style.width = '180px' // 绑定输入事件,值变化时触发ag-grid重新执行筛选 this.searchInput.addEventListener('input', () => { this.currentInputValue = this.searchInput.value.trim().toLowerCase() params.filterChangedCallback() }) this.rootDom.appendChild(this.searchInput) } // 告知ag-grid当前筛选是否处于激活状态 isFilterActive() { return this.currentInputValue !== '' } // 核心筛选判断逻辑 doesFilterPass(rowNode) { // 第一步:根据当前输入,计算所有命中的lookup条目对应的key集合 const matchedKeys = this.attachedLookupList.filter(item => // 遍历条目下所有token,只要任意token包含当前输入内容,就算命中 item.tokens.some(token => token.toLowerCase().includes(this.currentInputValue)) ).map(item => item.key) // 第二步:读取当前行对应列的单元格值,判断是否在命中集合内 const currentCellValue = this.agGridParams.valueGetter ? this.agGridParams.valueGetter(rowNode) : rowNode.data[this.agGridParams.colDef.field] return matchedKeys.includes(currentCellValue) } // 以下是ag-grid要求必须实现的模型同步方法,支持筛选状态持久化、清空按钮联动 getModel() { return { inputValue: this.currentInputValue } } setModel(model) { if (!model) return this.currentInputValue = model.inputValue this.searchInput.value = this.currentInputValue } afterGuiAttached() { this.searchInput.focus() } getGui() { return this.rootDom } }
列定义接入配置
在需要启用lookup搜索的列上,指定使用自定义筛选组件,并通过filterParams传入对应列的映射规则即可:
const tableColumnDefs = [ { field: 'name', headerName: '人员姓名', // 绑定自定义lookup筛选组件 filter: LookupFilter, // 传入当前列匹配的lookup映射 filterParams: { lookupMapping: lookupMapping } }, // 其余列正常配置即可 ]
适配调整说明
- 现有逻辑默认做了大小写兼容处理,输入大小写不影响匹配结果
- 匹配逻辑为「token包含输入值即命中」,完全支持输入片段、关联值搜索的场景,无需输入和token完全一致
- 组件本身支持多列复用,不同列只需传入对应的lookup映射即可,无需重复编写筛选逻辑
- 如果项目使用了第三方UI组件库,可将原生input替换为组件库的输入控件,只需在输入值变化时调用
filterChangedCallback触发筛选刷新即可
内容的提问来源于stack exchange,提问作者Catalina
相关产品推荐
相关产品推荐

