移动端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>

然后样式就比较好设置了

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

相关推荐
trsoliu1 分钟前
2025年Web前端最新趋势:React基金会成立、AI编码助手崛起与Astro极速搜索
前端·javascript·react.js
一 乐4 分钟前
商城推荐系统|基于SprinBoot+vue的商城推荐系统(源码+数据库+文档)
前端·数据库·vue.js·spring boot·后端·商城推荐系统
苹果电脑的鑫鑫5 分钟前
微信小程序原生如何使用画布生成名片
微信小程序·小程序
亿元程序员10 分钟前
为什么游戏公司现在都喜欢用protobuf?
前端
鹏多多12 分钟前
React瀑布流Masonry-Layout插件全方位指南:从基础到进阶实践
前端·javascript·react.js
fruge19 分钟前
前端数据可视化实战:Chart.js vs ECharts 深度对比与实现指南
前端·javascript·信息可视化
卓码软件测评28 分钟前
借助大语言模型实现高效测试迁移:Airbnb的大规模实践
开发语言·前端·javascript·人工智能·语言模型·自然语言处理
IT_陈寒33 分钟前
SpringBoot 3.0实战:这套配置让我轻松扛住百万并发,性能提升300%
前端·人工智能·后端
♡喜欢做梦34 分钟前
Spring Web MVC 入门秘籍:从概念到实践的快速通道(上)
前端·spring·mvc
Dragon Wu42 分钟前
Taro 自定义tab栏和自定义导航栏
前端·javascript·小程序·typescript·前端框架·taro