使用自定义表格头实现筛选:为何和如何

在使用 view-ui-plus(iView 的 Vue 3 版本)时,发现原生的表格组件不支持自定义输入筛选条件

为什么要使用自定义表格头?

原生组件的限制

view-ui-plus 的表格组件提供了基本的功能,但在原生实现中,对于复杂的筛选条件或输入框的支持较为有限。原生的筛选功能通常依赖于简单的下拉选择或预定义的筛选选项,这在处理自定义需求时显得不够灵活。

实现自定义筛选功能

下面是一个使用自定义表格头实现筛选的示例代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
{
title: '标题',
key: 'taskCount',
width: 200,
renderHeader: (h, { column }) => {
return h('div', { style: { display: 'flex', alignItems: 'center' } }, [
h(
'span',
{
style: {
marginRight: '8px',
cursor: 'default' // 默认光标样式
},
on: {
mouseenter: (event) => {
event.target.style.cursor = 'pointer' // 鼠标移入时变为手型光标
},
mouseleave: (event) => {
event.target.style.cursor = 'default' // 鼠标移出时恢复为默认光标
}
}
},
column.title
), // 显示标题
h(
Poptip,
{
placement: 'bottom',
width: 'auto',
trigger: 'click',
transfer: true
},
{
default: () =>
h(
'span',
{
style: {
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
cursor: 'pointer' // 确保 Poptip 触发区域的光标样式为手型
}
},
[
h('i', {
class: 'ivu-icon ivu-icon-ios-funnel',
style: {
fontSize: '14px',
color: '#B9BCCD'
}
})
]
),
content: () =>
h('div', { style: { display: 'flex', flexDirection: 'column', padding: '8px' } }, [
h(
Input,
{
placeholder: '请输入',
type: 'number',
style: { width: '110px', minWidth: '40px' },
onInput: (e) => {
console.log('Input value:', e)
}
},
{
suffix: () =>
h(
'span',
{
style: {
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
height: '100%',
fontSize: '14px'
}
},
[h('span', '≥')]
)
}
)
])
}
)
])
}
}

解释说明

  • renderHeader: 自定义列头的渲染方法。在这里我们通过 Flex 布局将标题和筛选图标组合在一起。
  • Poptip: 用于显示筛选输入框的弹出提示组件。通过点击触发弹出,并提供筛选输入区域。
  • Input: 用于输入筛选条件的组件。可以根据需要调整其样式和行为。

这里只做了一个大于等于条件的自定义筛选,要支持其他更多条件,只需要按照以上demo,使用h函数继续丰富对应的内容即可。
transfer: true
transfer
将弹层放置于 body 内,在 Tabs、带有 fixed 的 Table 列内使用时,建议添加此属性,它将不受父级样式影响,从而达到更好的效果。
如果不添加,会无法触发点击事件。