欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 明星 > Vue3实现表格搜索内容高亮

Vue3实现表格搜索内容高亮

2025/2/24 10:58:32 来源:https://blog.csdn.net/weixin_45280713/article/details/145206364  浏览:    关键词:Vue3实现表格搜索内容高亮

采用html拼接

v-html 指令用来将给定的 HTML 字符串直接渲染到页面上

<template><div><!-- 搜索框 --><input v-model="searchText" placeholder="搜索内容" /><!-- 表格 --><el-table :data="tableData" style="width: 100%" @row-click="handleRowClick"><el-table-column label="Content" prop="content"><template #default="{ row }"><!-- 使用 v-html 渲染含有高亮部分的 HTML --><span v-html="getHighlightedContent(row.content)"></span></template></el-table-column></el-table></div>
</template><script lang="ts" setup>import { ref } from 'vue';// 响应式数据const searchText = ref('');const tableData = ref([{ id: 1, content: '创建人:李四<br>创建时间:2025-01-11 10:24:00<br>' },{ id: 2, content: '创建人:张三<br>创建时间:2025-01-12 11:25:00<br>' },]);// 根据搜索文本匹配并返回高亮内容function getHighlightedContent(content: string) {if (!searchText.value) {return content; // 如果没有输入搜索文本,直接返回原内容}const regex = new RegExp(`(${escapeRegExp(searchText.value)})`, 'gi');let highlightedContent = content.replace(regex, '<span style="color: rgb(109,172,246); font-weight: bold;">\$1</span>');return highlightedContent;}// 用来转义搜索文本中的特殊字符,避免正则错误function escapeRegExp(string: string) {return string.replace(/[.*+?^=!:${}()|\[\]\/\\]/g, '\\$&');}
</script><style scoped>/* 你可以根据需要添加其他样式 */
</style>
(1)getHighlightedContent 函数
function getHighlightedContent(content: string) {if (!searchText.value) {return content; // 如果没有输入搜索文本,直接返回原内容}const regex = new RegExp(`(${escapeRegExp(searchText.value)})`, 'gi');let highlightedContent = content.replace(regex, '<span style="color: rgb(109,172,246); font-weight: bold;">\\$1</span>');return highlightedContent;
}
  • 这个函数接收一个字符串 content,并根据 searchText 中的文本进行高亮显示。
  • 步骤
    • 如果 searchText 为空,直接返回原内容。
    • 创建一个正则表达式,用于匹配 searchText 中的所有文本(不区分大小写)。
    • 使用 content.replace() 方法,找到所有匹配的文本并用 <span> 标签包裹,同时设置样式(字体加粗,颜色改变)。
    • 返回高亮后的 HTML 字符串。
(2)escapeRegExp 函数
function getHighlightedContent(content: string) {if (!searchText.value) {return content; // 如果没有输入搜索文本,直接返回原内容}const regex = new RegExp(`(${escapeRegExp(searchText.value)})`, 'gi');let highlightedContent = content.replace(regex, '<span style="color: rgb(109,172,246); font-weight: bold;">\\$1</span>');return highlightedContent;
}
  • 这个函数用于转义 searchText 中的特殊字符,避免它们在构建正则表达式时引起错误。
  • 正则表达式中的一些字符(如 .*? 等)具有特殊含义,因此需要通过 escapeRegExp 函数将它们转义,以确保它们能被正确地作为普通字符匹配。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词