【uniapp】vue2 搜索文字高亮显示
我这里是把方法放在公共组件中使用
javascript
props: {
// 帖子list
postList: {
type: Array,
required: true
},
// 搜索文本字体高亮
highLightSearch: {
type: String,
required: false
}
},
watch: {
// 监听 props 的变化
postList: {
immediate: true,
handler(newVal) {
// 变化后的新值, 当前的高亮搜索词
this.updateHighlightedPostList(newVal, this.highLightSearch);
},
},
},
methods: {
updateHighlightedPostList(postList, searchKeyword) {
// 检查是否有搜索关键字
if (!searchKeyword) {
this.highlightedPostList = [...postList]
return
}
// 创建正则表达式匹配关键字(g 全局匹配,i 不区分大小写)
const regex = new RegExp(`(${searchKeyword})`, "gi");
// 更新高亮内容
this.highlightedPostList = postList.map((item) => ({
...item,
title: item.title.replace(
regex,
`<text class="hight_blue">$1</text>` // 将匹配到的内容 ($1) 包裹在 <text> 标签中
),
}));
},
}
html
<view v-for="p in highlightedPostList" :key="p.id">
<!-- 页面文字展示一定要用 v-html 便于解析标签样式 -->
<view v-html="p.title" class=""></view>
</view>
高亮实现方式是用 HTML 标签包裹匹配文本,通过 CSS 控制样式
注意事项:
使用 v-html
显示 title
时要小心 XSS 攻击,确保 searchKeyword
是可信的
如果 postList
很大,频繁更新可能影响性能,可以考虑防抖
正则表达式中的特殊字符可能需要转义