使用正则表达式:
html
<template>
<div>
<input type="text" v-model="searchText" @input="filterItems">
<ul>
<li v-for="item in filteredItems" :key="item.id">
<span v-html="highlightText(item.text)"></span>
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
searchText: '',
items: [
{ id: 1, text: '苹果' },
{ id: 2, text: '香蕉' },
{ id: 3, text: '橙子' },
{ id: 4, text: '苹果派' },
{ id: 5, text: '橙汁' },
],
};
},
computed: {
filteredItems() {
if (this.searchText === '') {
return this.items;
}
return this.items.filter(item => item.text.includes(this.searchText));
},
},
methods: {
highlightText(value) {
const regex = new RegExp(this.searchText, 'gi');
return value.replace(regex, '<span class="highlight">$&</span>');
},
},
};
</script>
<style>
.highlight {
color: blue;
}
</style>
在上面的示例中,我们使用了一个方法 highlightText
来处理文字高亮。在模板中,我们使用 v-html
指令来渲染带有HTML标签的内容,从而将匹配的部分用 <span>
标签包裹起来,并添加 .highlight
类来设置文字颜色为蓝色。 无论使用过滤器还是正则表达式,你都可以根据实际需求来选择适合的方法来实现模糊搜索框中搜索内容与下拉框重复的文字变成蓝色。
在我的项目中模糊筛选用的时vue中<el-autocomplete>的方法,我使用了他的插槽
<el-form-item label="授权店铺">
<el-autocomplete
v-model.trim="shopName"
:clearable="true"
:fetch-suggestions="querySearchAsync"
placeholder="请输入授权店铺"
@select="handleSelect"
>
<template slot-scope="{ item }"> //item为数组元素,Object
<div>{{ item.address }}</div> //下拉列表显示的值已更改为address值
</template>
</el-autocomplete>
在这个做了一点改变,将
<div>{{ item.address }}</div> //改变为
<div v-html="highlightText(item.text)"></div>
这样就可以改变下拉框中每一行的代码样式,让他高亮显示。