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

然后样式就比较好设置了

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

相关推荐
特严赤傲20 小时前
在 Vue 中 v-for的写法对语法高亮的影响
前端·javascript·vue.js
PBitW20 小时前
从前端工程师的角度将SEO做到极致 -- 菜鸟来实操
前端·seo
雨雨雨雨雨别下啦20 小时前
【从0开始学前端】vue3路由,Pinia,组件通信
前端·vue.js·vue
调皮LE20 小时前
前端 HTML 转 PDF
前端
Nan_Shu_61420 小时前
熟悉RuoYi-Vue-Plus-前端 (1)
前端·javascript·vue.js
23124_8020 小时前
网络管理-1
运维·服务器·前端
PBitW20 小时前
Electron 初体验
前端·electron·trae
D***M97620 小时前
WebSpoon9.0(KETTLE的WEB版本)编译 + tomcatdocker部署 + 远程调试教程
前端
南囝coding20 小时前
《独立开发者精选工具》第 023 期
前端·后端·开源
文心快码BaiduComate20 小时前
Agent如何重塑跨角色协作的AI提效新范式
前端·后端·程序员