做uinapp项目需要做这种搜索,然后结果需要高亮搜索的文字。如下图这种:
这边用的uview组件库的搜索, 键盘回车搜索
<u-search placeholder="搜索问题" v-model="keyword" actionText="取消" @search="search"></u-search>
<view style="margin-top: 50rpx;" v-if="seacrhList.length">
<view class="seacrhList" v-for="(item, index) in seacrhList" :key="index"
v-html="brightenKeyword(item.title,editKeyword)">
{{item.title}}
</view>
</view>
data() {
return {
keyword: '', //搜索的文字
editKeyword: '', //做匹配的文字(这个一定要,不能用‘keyword’变量,不然会有问题)
seacrhList: [], //搜索的结果
list: [{title: '123456'},{title: '56789'}] //这里假如是接口返回的数据
}
},
methods: {
search() {
if (!this.keyword.trim()) {
//这里你要给个弹窗或者轻提示'请输入关键词'
return
}
//这个地方要请求接口,我们现在直接用模拟的数据list
//MINE_API.getHelpSearch({
// helpTitle: this.keyword
//}).then(res => {
// this.editKeyword = this.keyword
// this.seacrhList = res.data.records
//})
this.editKeyword = this.keyword
this.seacrhList = this.list //这个是接口搜索到的数据赋值
},
brightenKeyword(val, editKeyword ) {
const Reg = new RegExp(editKeyword);
if (val) {
const res = val.replace(Reg, `<span style="color: #D7311E;">${editKeyword }</span>`);
return res;
}
},
}
<style>
.seacrhList {
margin-top: 30rpx;
padding-bottom: 20rpx;
border-bottom: 1rpx solid #ddd;
}
</style>