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

然后样式就比较好设置了

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

相关推荐
carry杰10 分钟前
nacos bootstrap.yml 动态配置开发测试线上模式
前端·bootstrap·html
少年张二狗17 分钟前
Vue + Element-UI 图片上传实现拖拽排序功能
前端·vue.js·ui
我又来搬代码了27 分钟前
【Android】【Compose】Compose知识点复习(一)
android·前端·kotlin·android studio
哆啦A梦158831 分钟前
【vue实战】商城后台管理系统 01 项目介绍
前端·javascript·vue.js
爱吃土豆的马铃薯ㅤㅤㅤㅤㅤㅤㅤㅤㅤ1 小时前
java实现登录:多点登录互踢,30分钟无操作超时
java·前端
一字白首1 小时前
Vue Router 进阶,声明式 / 编程式导航 + 重定向 + 404 + 路由模式
前端·javascript·vue.js
广州华水科技1 小时前
单北斗变形监测在水库安全中的应用与维护该如何实施?
前端
计算机毕设指导61 小时前
基于微信小程序的积分制零食自选平台【源码文末联系】
java·spring boot·mysql·微信小程序·小程序·tomcat·maven
GIS好难学1 小时前
0帧起手《Vue零基础教程》,从前端框架到GIS开发系列课程
前端·vue.js·前端框架