在数据展示类应用中,搜索功能是提升用户体验的关键模块,而关键字高亮则能让搜索结果更加直观醒目。本文将详细介绍如何在 Element UI 框架中实现表格数据的搜索与关键字高亮功能,并结合树形表格的特性提供完整解决方案。
一、功能实现背景与核心需求
当表格中存在大量数据时,用户需要通过搜索快速定位目标内容。关键字高亮的核心价值在于:
- 明确标识搜索结果的位置,减少用户视觉扫描成本
- 增强交互反馈,让搜索操作更具即时性
- 提升数据可读性,尤其是在复杂表格结构中
结合用户提供的代码,我们需要实现以下核心功能:
- 搜索输入框的双向绑定与事件监听
- 表格数据中指定列的关键字匹配
- 匹配文本的样式高亮处理
- 树形表格结构下的递归高亮处理
二、核心代码实现与解析
1. 搜索组件与表格结构
首先看用户提供的基础代码结构,搜索输入框与表格的集成方式:
<el-form-item label="搜索内容:">
<el-input v-model="searchForm.searchContent" placeholder="请输入搜索内容"></el-input>
</el-form-item>
<div class="table-container">
<el-table :data="visibleTableData" border style="width: 99%;" max-height="650px"
:tree-props="{ children: 'details' }" row-key="id" @selection-change="handleSelectionChange">
<!-- 表格列定义... -->
<el-table-column align="center" label="资料内容" prop="content">
<template #default="scope">
<span v-html="highlightText(scope.row.content, searchKeyword)"></span>
</template>
</el-table-column>
<!-- 其他需要高亮的列... -->
</el-table>
</div>
关键点解析:
- 通过
v-model
实现搜索输入框与searchForm.searchContent
的双向绑定 - 表格使用
:tree-props
配置树形结构,支持父子节点嵌套 - 需要高亮的列通过
v-html
渲染高亮后的文本,结合highlightText
方法处理
2. 关键字高亮核心方法
下面是 highlightText
方法的完整实现,建议添加到 Vue 实例的 methods
中:
methods: {
// 关键字高亮处理方法
highlightText(text, keyword) {
// 处理空值或非字符串类型
if (!text || typeof text !== 'string') return text;
if (!keyword || typeof keyword !== 'string') return text;
// 转义正则表达式特殊字符
const escapedKeyword = keyword.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
// 创建不区分大小写的全局匹配正则
const regex = new RegExp(escapedKeyword, 'gi');
// 使用span包裹匹配内容并添加高亮样式
return text.replace(regex, (match) => {
return `<span class="highlight">${match}</span>`;
});
},
// 搜索事件处理
handleSearch() {
// 获取搜索关键字
this.searchKeyword = this.searchForm.searchContent.trim();
// 执行搜索过滤(此处需根据实际数据结构实现)
this.filterTableData();
},
// 表格数据过滤方法
filterTableData() {
if (!this.searchKeyword) {
// 清空搜索时显示全部数据
this.visibleTableData = [...this.originalTableData];
return;
}
// 递归过滤树形表格数据(示例逻辑,需根据实际数据结构调整)
this.visibleTableData = this.originalTableData.filter(item => {
return this.checkRowMatch(item, this.searchKeyword);
});
},
// 检查行数据是否匹配搜索条件
checkRowMatch(row, keyword) {
// 检查当前行需要高亮的字段
const fields = ['content', 'projectName', 'form', 'receiverName'];
for (const field of fields) {
if (row[field] && row[field].toString().includes(keyword)) {
return true;
}
}
// 递归检查子节点
if (row.details && row.details.length > 0) {
for (const child of row.details) {
if (this.checkRowMatch(child, keyword)) {
return true;
}
}
}
return false;
}
}
3. 高亮样式定制
为了让高亮效果更明显,需要在 CSS 中添加高亮样式:
css
.highlight {
background-color: #ffeb3b; /* 黄色背景,可自定义 */
color: #333;
font-weight: 500;
padding: 0 2px;
border-radius: 2px;
}
三、总结与扩展方向
通过上述方法,我们实现了 Element UI 表格中的关键字高亮功能,核心在于利用正则表达式替换匹配文本,并结合树形结构的递归处理。
