element的el-autocomplete带输入建议搜索+搜索匹配文字高亮显示
直接上代码
<el-autocomplete
clearable
placeholder="请输入关键词进行搜索"
@input="searchInput"
v-model="searchInputData"
:fetch-suggestions="querySearchAsync"
>
<i slot="prefix" class="el-input__icon el-icon-search"></i>
<template slot-scope="{ item }">
<div v-html="highlightText(item.value)"></div>
</template>
</el-autocomplete>
querySearchAsync(queryString, cb) {
var cardData = this.cardData;
var results = queryString
? cardData.filter(this.createStateFilter(queryString))
: cardData;
this.resultsArr = [];
results.forEach((item) => {
this.resultsArr.push({ value: item.name });
});
cb(this.resultsArr);
},
createStateFilter(queryString) {
return (item) => {
return item.name.toLowerCase().includes(queryString.toLowerCase());
};
},
highlightText(value) {
if (this.searchInputData != "") {
const regex = new RegExp(`(${this.searchInputData})`, "gi");
return value.replace(regex, '<span style="color: #2773FF;">$1</span>');
} else {
return value;
}
},
效果图