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

然后样式就比较好设置了

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

相关推荐
七月丶几秒前
🚀 前端缓存踩坑指南:如何优雅地解决浏览器缓存问题?
前端
沉默王二1 分钟前
更快更强!字节满血版DeepSeek在IDEA中真的爽!
java·前端·程序员
bug总结2 分钟前
uniapp+微信小程序+地图+传入多个标记点显示+点击打开内置地图导航+完整代码
uni-app
码农研究僧5 分钟前
Uniapp 页面返回不刷新?两种方法防止 onShow 触发多次请求!
uni-app·vue·html·onshow
掘金酱7 分钟前
👏 用idea传递无限可能!AI FOR CODE挑战赛「创意赛道」作品提交指南
前端·人工智能·trae
Hamm10 分钟前
咦,你的Git仓库贡献者里怎么有这么多大佬???
前端·git·github
陈卓41042 分钟前
Redis-限流方案
前端·redis·bootstrap
顾林海1 小时前
Flutter Dart 运算符全面解析
android·前端
低代码布道师1 小时前
加油站小程序实战教程08动态获取城市和站点信息
低代码·小程序
七月丶1 小时前
🚀 现代 Web 开发:如何优雅地管理前端版本信息?
前端