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

然后样式就比较好设置了

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

相关推荐
万少3 分钟前
记第一次鸿蒙应用上架之旅:一场略带遗憾的旅途
前端·harmonyos
鹏多多5 分钟前
H5开发避坑!解决Safari浏览器的video会覆盖z-index:1的绝对定位元素
前端·javascript·vue.js
恋猫de小郭13 分钟前
来了解一下,为什么你的 Flutter WebView 在 iOS 26 上有点击问题?
android·前端·flutter
charlie11451419116 分钟前
CSS学习笔记5:CSS 盒模型 & Margin 注意事项
前端·css·笔记·学习·教程
CodeSheep16 分钟前
稚晖君公司的最新工资和招人标准
前端·后端·程序员
亿元程序员21 分钟前
今天我去面试游戏开发,说我回答得不全面...
前端
小小王app小程序开发30 分钟前
盲盒抽赏小程序一番赏 + 无限赏拓展玩法分析:技术赋能与商业破局
小程序
一只小阿乐34 分钟前
vue3封装alert 提示组件 仿element-plus
前端·javascript·vue.js·vue3
IT_陈寒1 小时前
SpringBoot实战避坑指南:我在微服务项目中总结的12条高效开发经验
前端·人工智能·后端
华洛1 小时前
解读麦肯锡报告:Agent落地的六大经验教训
前端·javascript·产品经理