Vxe-Grid表格筛选实战:3种自定义渲染器实现复杂业务过滤(附完整代码)
最近在重构一个后台管理系统时,遇到了一个挺有意思的需求:产品经理希望表格的筛选功能能“聪明”一点。比如,用户角色列需要支持搜索后多选,年龄列要能进行数值范围比较,而姓名列则要支持模糊匹配。用Vxe-Grid自带的筛选器吧,功能上总觉得差那么点意思;完全自己从头写一个吧,又怕破坏了组件库的整体性和性能。纠结之下,我决定深入研究一下Vxe-Grid的自定义筛选渲染器机制。
没想到,这一挖还真挖出了不少宝藏。Vxe-Grid提供的filterRender扩展能力,其灵活程度远超我的预期。它允许你几乎完全接管筛选界面的渲染逻辑和筛选判断逻辑,但同时又替你管理好了状态、事件绑定这些脏活累活。今天,我就结合那次项目实战,和你详细聊聊如何利用三种典型的自定义渲染器——FilterInput(文本搜索)、FilterContent(多选下拉)和FilterComplex(数值比较),来搞定那些看似棘手的业务过滤需求。我会附上完整的、可直接复用的代码,并分享几个我踩过坑后才总结出来的性能优化和状态保持技巧。
1. 理解Vxe-Grid筛选渲染器的核心机制
在动手写代码之前,我们得先搞清楚Vxe-Grid的筛选器是怎么工作的。这就像你要改装一辆车,总得先看懂它的发动机和传动系统吧?Vxe-Grid的筛选体系可以粗略地分为两层:配置层和渲染执行层。
配置层就是我们熟悉的columns定义里的filters和filterRender属性。filters数组定义了筛选的“数据模型”,而filterRender则指定了用哪个“视图组件”来渲染筛选界面。这里有个关键点:filters[0].data这个对象,它是连接配置层和渲染层的桥梁,也是我们存储自定义筛选状态的核心位置。
// 在column配置中
{
field: 'age',
title: '年龄',
filters: [{
data: { type: 'lt', value: '' } // 这个data对象将被传递到自定义渲染器
}],
filterRender: { name: 'FilterComplex' } // 指定使用我们注册的渲染器
}
渲染执行层的核心是VXETable.renderer.add方法。注册一个渲染器时,你需要提供几个关键方法:
renderFilter: 负责渲染筛选弹出框里的UI。这里你可以使用任何Vue组件,完全自由。filterMethod: 这是筛选的“裁判”。每一行数据都会经过这个方法的判断,返回true则显示,false则过滤掉。它的参数里包含了当前筛选条件(option.data)和当前行数据(row)。filterResetMethod: 当用户点击重置按钮时调用,用于将option.data重置为初始状态。
提示:
filterMethod的执行频率很高,尤其是在大数据集或复杂筛选条件下。务必保证这个方法内的逻辑高效,避免进行不必要的计算或DOM操作,这是影响表格性能的关键点之一。
理解了这套机制,我们就可以像搭积木一样,为不同的业务场景组装不同的筛选器了。下面这个表格概括了三种典型场景下,我们该如何选择和使用不同的渲染器:
| 筛选场景 | 适用渲染器类型 | 核心交互 | 数据存储结构 (option.data) | 适用字段示例 |
|---|---|---|---|---|
| 简单文本匹配 | FilterInput | 单行输入框,支持实时筛选或回车确认 | String (搜索关键词) | 姓名、编号、地址 |
| 多值精确匹配 | FilterContent | 下拉列表,支持搜索、全选/反选 | { vals: Array, sVal: String } | 状态、类型、所属部门 |
| 数值范围比较 | FilterComplex | 单选按钮组+输入框,定义比较关系 | { type: String, value: String/Number } | 年龄、金额、数量、得分 |
2. 实战一:FilterInput - 实现高效文本模糊搜索
文本搜索是最基础的需求,但做好也不容易。Vxe-Grid自带的筛选输入框功能比较单一,我们经常需要支持中文输入法、防抖或者实时搜索。通过自定义FilterInput,我们可以轻松实现这些增强功能。
首先,我们注册这个渲染器。它的逻辑相对简单,filterMethod就是判断行数据是否包含关键词。
// filter-renderers.js
import VXETable from 'vxe-table'
import XEUtils from 'xe-utils'
VXETable.renderer.add('FilterInput', {
// 筛选模板 - 这里我们将渲染一个自定义的Vue组件
renderFilter (h, renderOpts, params) {
return [
h('FilterInput', { props: { params } })
]
},
// 筛选方法 - 核心逻辑
filterMethod ({ option, row, column }) {
const keyword = option.data // 这里data直接是字符串
const cellValue = XEUtils.get(row, column.property)
// 进行不区分大小写的模糊匹配
if (keyword && cellValue != null) {
return cellValue.toString().toLowerCase().includes(keyword.toLowerCase())
}
// 如果关键词为空,则显示所有行
return true
},
// 重置方法
filterResetMethod ({ options }) {
options.forEach(option => {
option.data = '' // 重置为空字符串
})
}
})
接下来是FilterInput.vue组件。这里我加入了一个实用的功能:防抖。在用户连续输入时,不会频繁触发筛选,而是在停止输入一段时间后才执行,这对性能很友好。
<!-- FilterInput.vue -->
<template>
<div class="custom-filter-input">
<vxe-input
v-model="keyword"
type="text"
placeholder="输入关键词搜索 (支持实时筛选)"
clearable
@input="handleInput"
@keyup.enter="confirmFilter"
>
<template #suffix>
<i class="vxe-icon--search" @click="confirmFilter"></i>
</template>
</vxe-input>
</div>
</template>
<script>
import { debounce } from 'lodash-es' // 使用lodash的防抖函数,也可自己实现
export default {
name: 'FilterInput',
props: {
params: Object
},
data () {
return {
keyword: '',
// 创建防抖函数,延迟300毫秒执行
debouncedFilter: debounce(this.doFilter, 300)
}
},
created () {
// 初始化时从column配置中读取已存在的筛选值
const { column } = this.params
if (column.filters && column.filters[0]) {
this.keyword = column.filters[0].data || ''
}
},
methods: {
handleInput () {
// 输入时更新column的筛选数据
const { column } = this.params
if (column.filters && column.filters[0]) {
column.filters[0].data = this.keyword
}
// 触发防抖筛选
this.debouncedFilter()
},
doFilter () {
// 实际触发筛选的方法
const { $panel } = this.params
// changeOption用于更新筛选面板的勾选状态
$panel.changeOption(null, !!this.keyword, column.filters[0])
// confirmFilter执行真正的筛选
$panel.confirmFilter()
},
confirmFilter () {
// 回车或点击搜索图标时立即执行,取消防抖
this.debouncedFilter.cancel()
this.doFilter()
}
}
}
</script>
<style scoped>
.custom-filter-input {
padding: 12px;
min-width: 180px;
}
</style>
在实际使用中,你只需要在定义列时指定这个渲染器即可:
columns: [
{
field: 'name',
title: '姓名',
filters: [{ data: '' }], // 初始数据为空字符串
filterRender: { name: 'FilterInput' } // 指定渲染器
}
]
3. 实战二:FilterContent - 构建动态多选下拉筛选器
对于像“用户角色”、“产品状态”这类枚举值字段,多选下拉筛选是最佳交互。Vxe-Grid自带的多选筛选器功能已经不错,但有时我们需要从服务器动态加载选项,或者选项列表非常长,需要集成搜索功能。这时,自定义FilterContent渲染器就派上用场了。
这个渲染器的核心在于,filterMethod需要判断行数据是否在用户选择的vals数组中。
// filter-renderers.js
VXETable.renderer.add('FilterContent', {
isFooter: false, // 不显示默认的“确定”“重置”底部按钮,我们用自定义的
renderFilter (h, renderOpts, params) {
return [
h('FilterContent', { props: { params } })
]
},
filterMethod ({ option, row, column }) {
const { vals } = option.data // vals是选中的值数组
const cellValue = XEUtils.get(row, column.property)
// 如果未选择任何值,则显示所有行
if (!vals || vals.length === 0) {
return true
}
// 判断当前行的值是否在选中数组中
return vals.includes(cellValue)
},
filterResetMethod ({ options }) {
options.forEach(option => {
// 重置时清空选中数组和搜索词
option.data = { vals: [], sVal: '' }
})
}
})
FilterContent.vue组件是重头戏,它需要实现搜索、全选、动态加载选项等复杂交互。下面的代码实现了一个功能完整的版本:
<!-- FilterContent.vue -->
<template>
<div class="custom-filter-content">
<!-- 搜索框 -->
<div class="search-section">
<vxe-input
v-model="searchText"
placeholder="搜索选项..."
clearable
@input="handleSearch"
>
<template #suffix>
<i class="vxe-icon--search"></i>
</template>
</vxe-input>
</div>
<!-- 选项列表 -->
<div class="options-section">
<div class="option-item select-all">
<vxe-checkbox
:indeterminate="isIndeterminate"
:checked="isAllSelected"
@change="handleSelectAll"
>
全选
</vxe-checkbox>
</div>
<div class="options-list">
<div
v-for="option in filteredOptions"
:key="option.value"
class="option-item"
>
<vxe-checkbox
v-model="option.checked"
@change="handleOptionChange(option)"
>
{{ option.label }}
</vxe-checkbox>
</div>
<div v-if="filteredOptions.length === 0" class="empty-tip">
无匹配项
</div>
</div>
</div>
<!-- 自定义底部按钮 -->
<div class="footer-section">
<vxe-button size="small" @click="handleConfirm">筛选</vxe-button>
<vxe-button size="small" type="text" @click="handleReset">重置</vxe-button>
</div>
</div>
</template>
<script>
import XEUtils from 'xe-utils'
export default {
name: 'FilterContent',
props: {
params: Object
},
data () {
return {
searchText: '',
// 所有可能的选项(可从后端获取)
allOptions: [],
// 当前显示的选项(根据搜索过滤)
filteredOptions: [],
// 当前选中的值数组
selectedVals: []
}
},
computed: {
// 计算是否“全选”
isAllSelected () {
if (this.filteredOptions.length === 0) return false
return this.filteredOptions.every(opt => opt.checked)
},
// 计算是否为“部分选中”状态
isIndeterminate () {
const checkedCount = this.filteredOptions.filter(opt => opt.checked).length
return checkedCount > 0 && checkedCount < this.filteredOptions.length
}
},
created () {
this.initOptions()
},
methods: {
// 初始化选项列表:可以从当前表格数据中提取唯一值,也可以从API加载
initOptions () {
const { $table, column } = this.params
const { fullData } = $table.getTableData()
// 从表格数据中提取该列的所有唯一值作为选项
const uniqueValues = [...new Set(fullData.map(row => XEUtils.get(row, column.property)))]
this.allOptions = uniqueValues.map(value => ({
value,
label: value,
checked: false
}))
// 读取已保存的筛选状态
const filterOption = column.filters[0]
if (filterOption && filterOption.data && filterOption.data.vals) {
this.selectedVals = filterOption.data.vals
// 根据已选值设置checkbox状态
this.allOptions.forEach(opt => {
opt.checked = this.selectedVals.includes(opt.value)
})
}
this.filteredOptions = [...this.allOptions]
},
handleSearch () {
// 根据搜索词过滤选项
if (!this.searchText.trim()) {
this.filteredOptions = [...this.allOptions]
} else {
const keyword = this.searchText.toLowerCase()
this.filteredOptions = this.allOptions.filter(opt =>
opt.label.toLowerCase().includes(keyword)
)
}
},
handleSelectAll (checked) {
// 全选/取消全选当前显示的所有选项
this.filteredOptions.forEach(option => {
option.checked = checked
})
this.updateSelectedVals()
},
handleOptionChange (changedOption) {
// 单个选项变化时更新选中数组
this.updateSelectedVals()
},
updateSelectedVals () {
// 从allOptions中计算所有被选中的值
this.selectedVals = this.allOptions
.filter(opt => opt.checked)
.map(opt => opt.value)
// 更新到column的筛选数据中
const { column } = this.params
if (column.filters && column.filters[0]) {
column.filters[0].data = {
vals: this.selectedVals,
sVal: this.searchText
}
}
},
handleConfirm () {
const { $panel, column } = this.params
const filterOption = column.filters[0]
// 更新筛选条件并执行筛选
$panel.changeOption(null, this.selectedVals.length > 0, filterOption)
$panel.confirmFilter()
},
handleReset () {
// 重置所有状态
this.searchText = ''
this.allOptions.forEach(opt => { opt.checked = false })
this.selectedVals = []
this.filteredOptions = [...this.allOptions]
// 调用渲染器的重置方法
const { $panel } = this.params
$panel.resetFilter()
}
}
}
</script>
<style scoped>
.custom-filter-content {
width: 240px;
padding: 8px;
user-select: none;
}
.search-section {
margin-bottom: 8px;
}
.options-section {
max-height: 280px;
overflow-y: auto;
border: 1px solid #dcdfe6;
border-radius: 4px;
padding: 4px;
}
.option-item {
padding: 6px 8px;
cursor: pointer;
}
.option-item.select-all {
border-bottom: 1px solid #e8e8e8;
margin-bottom: 4px;
padding-bottom: 8px;
}
.option-item:hover {
background-color: #f5f7fa;
}
.options-list {
padding-bottom: 4px;
}
.empty-tip {
text-align: center;
padding: 20px 0;
color: #909399;
font-size: 12px;
}
.footer-section {
display: flex;
justify-content: space-between;
margin-top: 12px;
padding-top: 8px;
border-top: 1px solid #e8e8e8;
}
</style>
这个组件的亮点在于它完全接管了筛选交互,提供了比原生更优的用户体验,特别是当选项很多时,搜索功能非常实用。
4. 实战三:FilterComplex - 实现灵活的数值比较筛选
对于数值型数据,我们经常需要“大于”、“小于”、“等于”这样的比较筛选。Vxe-Grid本身不支持这种模式,但通过FilterComplex渲染器,我们可以轻松实现。
首先注册渲染器,filterMethod会根据type和value执行不同的比较逻辑。
// filter-renderers.js
VXETable.renderer.add('FilterComplex', {
isFooter: false,
renderFilter (h, renderOpts, params) {
return [
h('FilterComplex', { props: { params } })
]
},
filterMethod ({ option, row, column }) {
const { type, value } = option.data
const cellValue = XEUtils.get(row, column.property)
// 如果未输入比较值,则显示所有行
if (value === '' || value == null) {
return true
}
const numValue = parseFloat(value)
const numCell = parseFloat(cellValue)
// 确保都是有效数字再比较
if (isNaN(numValue) || isNaN(numCell)) {
return false
}
switch (type) {
case 'gt': return numCell > numValue
case 'lt': return numCell < numValue
case 'eq': return numCell === numValue
case 'gte': return numCell >= numValue
case 'lte': return numCell <= numValue
default: return true
}
},
filterResetMethod ({ options }) {
options.forEach(option => {
option.data = { type: 'gt', value: '' }
})
}
})
对应的Vue组件需要提供比较运算符的选择和数值的输入:
<!-- FilterComplex.vue -->
<template>
<div class="custom-filter-complex">
<div class="operator-section">
<vxe-radio-group v-model="comparisonType" size="small">
<vxe-radio label="gt">大于</vxe-radio>
<vxe-radio label="lt">小于</vxe-radio>
<vxe-radio label="eq">等于</vxe-radio>
<vxe-radio label="gte">大于等于</vxe-radio>
<vxe-radio label="lte">小于等于</vxe-radio>
</vxe-radio-group>
</div>
<div class="value-section">
<vxe-input
v-model="inputValue"
type="number"
placeholder="输入数值"
clearable
@input="handleInputChange"
></vxe-input>
</div>
<div class="hint-section" v-if="inputValue">
<span class="hint-text">筛选: 年龄 {{ operatorMap[comparisonType] }} {{ inputValue }}</span>
</div>
<div class="footer-section">
<vxe-button
size="small"
:disabled="!inputValue"
@click="handleConfirm"
>
筛选
</vxe-button>
<vxe-button size="small" type="text" @click="handleReset">
重置
</vxe-button>
</div>
</div>
</template>
<script>
export default {
name: 'FilterComplex',
props: {
params: Object
},
data () {
return {
comparisonType: 'gt',
inputValue: '',
operatorMap: {
gt: '>',
lt: '<',
eq: '=',
gte: '≥',
lte: '≤'
}
}
},
created () {
// 初始化时读取已存在的筛选条件
const { column } = this.params
if (column.filters && column.filters[0] && column.filters[0].data) {
const { type, value } = column.filters[0].data
this.comparisonType = type || 'gt'
this.inputValue = value || ''
}
},
methods: {
updateFilterData () {
// 更新筛选条件到column配置
const { column } = this.params
if (column.filters && column.filters[0]) {
column.filters[0].data = {
type: this.comparisonType,
value: this.inputValue
}
}
},
handleInputChange () {
this.updateFilterData()
// 可以在这里加入防抖逻辑,实现实时筛选
},
handleConfirm () {
this.updateFilterData()
const { $panel, column } = this.params
const filterOption = column.filters[0]
$panel.changeOption(null, !!this.inputValue, filterOption)
$panel.confirmFilter()
},
handleReset () {
this.comparisonType = 'gt'
this.inputValue = ''
const { $panel } = this.params
$panel.resetFilter()
}
}
}
</script>
<style scoped>
.custom-filter-complex {
width: 220px;
padding: 12px;
}
.operator-section {
margin-bottom: 12px;
}
.value-section {
margin-bottom: 8px;
}
.hint-section {
margin-bottom: 12px;
padding: 6px;
background-color: #f0f9ff;
border-radius: 4px;
font-size: 12px;
color: #409eff;
}
.hint-text {
display: block;
text-align: center;
}
.footer-section {
display: flex;
justify-content: space-between;
margin-top: 12px;
padding-top: 8px;
border-top: 1px solid #e8e8e8;
}
</style>
在表格列定义中使用它:
{
field: 'age',
title: '年龄',
filters: [{
data: { type: 'gt', value: '' } // 初始状态:类型为“大于”,值为空
}],
filterRender: { name: 'FilterComplex' }
}
5. 性能优化与状态管理的进阶技巧
实现了基本功能后,我们还需要关注两个实际问题:性能和状态管理。尤其是在处理大型数据集或复杂筛选逻辑时,这些问题会变得突出。
性能优化方面,我总结了几个关键点:
-
filterMethod必须高效:这个方法会对每一行数据执行,避免在其中进行复杂的计算、DOM操作或异步调用。对于FilterContent,使用Set或Map来检查包含关系会比Array.includes()更快,尤其是选项很多时。// 优化后的filterMethod示例 filterMethod ({ option, row, column }) { const { vals } = option.data if (!vals || vals.length === 0) return true // 使用Set提高查找效率 const valSet = new Set(vals) const cellValue = XEUtils.get(row, column.property) return valSet.has(cellValue) } -
防抖与节流:对于
FilterInput这类实时筛选,一定要用防抖控制触发频率。我在前面的代码中已经演示了如何使用lodash的debounce。 -
虚拟滚动与分页:如果表格数据量极大(数万行),即使筛选逻辑再高效,渲染也会成为瓶颈。这时应考虑结合Vxe-Grid的虚拟滚动或后端分页。自定义筛选器需要适应这种场景,比如
FilterContent的选项列表可能无法从前端所有数据中生成,而需要从后端接口获取。
状态管理是另一个容易踩坑的地方。Vxe-Grid的筛选状态默认是内部管理的,但当我们使用自定义渲染器时,需要特别注意:
-
动态更新数据时的状态保持:如果你的表格数据是动态更新的(比如轮询、WebSocket推送),筛选状态可能会丢失。解决方案是在数据更新后,手动重新应用筛选条件。
// 在更新表格数据后 async function refreshTableData() { const newData = await fetchData() this.gridOptions.data = newData // 下一帧DOM更新后,重新应用当前所有列的筛选 this.$nextTick(() => { const $grid = this.$refs.xGrid if ($grid) { // 获取当前所有筛选条件 const filterConfigs = $grid.getFilterConfig() // 重新应用筛选 $grid.setFilterConfig(filterConfigs) } }) } -
多标签页或路由切换的状态保存:如果用户可能在筛选后跳转到其他页面再返回,你需要将筛选状态保存到
localStorage或Vuex中,并在组件mounted时恢复。// 保存筛选状态 function saveFilterState(gridRef, storageKey = 'table_filter_state') { const filterConfig = gridRef.getFilterConfig() localStorage.setItem(storageKey, JSON.stringify(filterConfig)) } // 恢复筛选状态 function restoreFilterState(gridRef, storageKey = 'table_filter_state') { const saved = localStorage.getItem(storageKey) if (saved) { try { const filterConfig = JSON.parse(saved) gridRef.setFilterConfig(filterConfig) } catch (e) { console.error('恢复筛选状态失败:', e) } } } -
自定义渲染器内部状态同步:确保渲染器组件内的状态(如输入框的值、复选框的选中状态)与
column.filters[0].data保持同步。我在上面的示例代码中,都在created钩子中读取了初始值,并在每次变化时更新了data对象。
最后,分享一个我遇到的实际问题:在FilterContent中,当表格数据变化导致选项列表变化时,如何保持用户已选中的选项?我的解决方案是在组件内部维护一个完整的选项映射,而不仅仅是当前显示的选项。当数据更新时,重新生成选项列表,但根据之前保存的选中状态来设置checked属性。这需要更精细的状态管理,但能提供更好的用户体验。
自定义筛选渲染器确实需要多写一些代码,但带来的灵活性和用户体验提升是值得的。特别是在面对复杂业务场景时,这种“可插拔”的设计让你能够精准地满足产品需求,而不是被组件库的限制所束缚。
96



被折叠的 条评论
为什么被折叠?



