移动端uni-app小程序搜索高亮前端处理,同时可设置相关样式,兼顾性能

在uni-app中我们会遇到搜索高亮显示的需求

如下图:

起初用的是富文本实现

使用replaceAll方法取代搜索字段为一个 标签并设置相应的样式,但是小程序的并没有把 标签渲染出来,所以放弃了,下面原代码:

javascript 复制代码
/* 搜索字体变色 */
export const searchColour = (text:string,searchKey:string)=>{
	return text.replaceAll(searchKey,`<text>${searchKey}</text>`)
}

用第三方库 mp-html 富文本组件

库的链接地址为:https://ext.dcloud.net.cn/plugin?id=805

这次将 渲染出来了,但里面的样式太难设置了,导致效果也不是很理想,所以放弃了

封装特定的高亮渲染组件

原理就是根据搜索字段,将渲染字符串转化为对象,标记高亮字段,然后分别渲染

下面上封装组件代码:

javascript 复制代码
<template>
	<text v-for="(item,index) in renderString" :key="index" :class="{'high-light':item.highLight}">{{item.text}}
	</text>
</template>

<script setup lang='ts'>
	import {
		computed
	} from "vue";
	const props = withDefaults(defineProps < {
		textString: string,
		searchValue: string
	} > (), {

	})
	const renderString = computed(() => {
		return getTextObj(props.textString, props.searchValue)
	})

	function getTextObj(str: string, searchKey: string) {
		let strObj = [];
		let index = 0;
		if (searchKey == '') {
			return [{
				text: str,
				highLight: false
			}]
		}

		while (index < str.length) {
			let pos = str.indexOf(searchKey, index);
			if (pos === -1) {
				strObj.push({
					text: str.slice(index),
					highLight: false
				});
				break;
			}
			if (pos !== 0) {
				strObj.push({
					text: str.slice(index, pos),
					highLight: false
				});
			}
			strObj.push({
				text: searchKey,
				highLight: true
			});
			index = pos + searchKey.length;
		}
		return strObj;
	}
</script>

<style lang='scss' scoped>
	.high-light {
		color: #DF2D45;
	}
</style>

然后样式就比较好设置了

有帮助到你的话,点个赞吧!

相关推荐
烛阴6 分钟前
C# 正则表达式(3):分组与捕获——从子串提取到命名分组
前端·正则表达式·c#
eason_fan1 小时前
从一则内存快照看iframe泄漏:活跃与Detached状态的回收差异
前端·性能优化
狗头大军之江苏分军1 小时前
年底科技大考:2025 中国前端工程师的 AI 辅助工具实战盘点
java·前端·后端
编程修仙2 小时前
第三篇 Vue路由
前端·javascript·vue.js
吴汉三2 小时前
iOS 和 HarmonyOS 兼容笔记
uni-app
比老马还六2 小时前
Bipes项目二次开发/硬件编程-设备连接(七)
前端·javascript
掘金一周2 小时前
前端一行代码生成数千页PDF,dompdf.js新增分页功能| 掘金一周 12.25
前端·javascript·后端
张就是我1065923 小时前
漏洞复现指南:利用 phpinfo() 绕过 HttpOnly Cookie 保护
前端
Kagol3 小时前
🎉TinyVue v3.27.0 正式发布:增加 Space 新组件,ColorPicker 组件支持线性渐变
前端·vue.js·typescript
潍坊老登3 小时前
大前端框架汇总/产品交互参考UE
前端