uniapp实现模糊搜索关键词高亮

1,065 阅读1分钟

实现思路

使用input的@input事件,可以在用户输入的时候及时请求接口并返回一些可供选择的关键词,但是要考虑节流,获取到接口返回的数据以后遍历,把与关键词相同的字符加一个样式类再通过v-html渲染。

<!-- 搜索框 -->
<view class='search'>
	<view class='input'>
		<input type='text' v-model='searchValue' :focus="focus" placeholder='搜索商品'
				@input="setValue" @confirm="searchBut"></input>
			<text class='font_family icon-sousuoye_sousuo' @tap='searchBut'></text>
	</view>
</view>
<!-- 展示筛选内容 -->
<view class="fuzzy_modal" :style="{height:fuzzyHeight + 'px',top:sysHeight + 56 + 'px'}" v-if="false">
	<view class="cell" v-for="(item,index) in newPartyList" :key="index">
		<view class="keyword" v-html="item.orgFullName"></view>
			<text class="font_family icon-sousuoye_sousuo"></text>
	</view>
</view>
setValue: Debounce(function(e){
	this.newPartySearch();
}),
newPartySearch() {
    //模拟接口返回
    this.newPartyList = [
        {orgFullName: '兰蔻'},
        {orgFullName: '兰蔻小黑瓶'},
        {orgFullName: '兰蔻面霜'},
        {orgFullName: '蔻驰女包'},
        {orgFullName: '蔻驰包'},
	];
    this.newPartyList.map((item) => {
    	item.orgFullName = this.brightKeyword(item.orgFullName);
    });
},
brightKeyword(val) {
	const keyword = this.searchValue;
	if (val.indexOf(keyword) > -1) {
		// replace() 方法用于在字符串中用一些字符替换另一些字符,或替换一个与正则表达式匹配的子串。
			return val.replace(keyword, `<span class="highlight">${keyword}</span>`);
	} else {
		return val;
	}
},
/**
 * 函数防抖 (只执行最后一次)
 * @param fn
 * @param delay
 * @returns {Function}
 * @constructor
 */
export const Debounce = (fn, t) => {
	const delay = t || 500
	let timer
	return function() {
		const args = arguments
		if (timer) {
			clearTimeout(timer)
		}
		timer = setTimeout(() => {
			timer = null
			fn.apply(this, args)
		}, delay)
	}
}

微信图片_20221020121858.jpg