背景:
因项目需要优化下拉框,选项特别多的情况下,想要根据关键字快速搜索出目标选中项结果。
实现效果图:
实现步骤以及关键代码:
1. 下拉搜索框(添加搜索属性、下拉框切换方法、下拉选项显示等等)
<div class="header-item">
<div class="w-60p">设备ID:</div>
<el-select v-model="deviceId" filterable :filter-method="dataFilter" @visible-change="visibleHideSelectInput" placeholder="请选择设备ID" class="header-item-inner-long">
<el-option v-for="item in deviceIdList" :key="item.value" :label="item.label" :value="item.value">
<div v-html="item.showItem"></div>
</el-option>
</el-select>
</div>
2. 定义属性名和下拉列表数组
deviceId: '',
deviceIdList: [], // 筛选后的下拉列表数组
deviceIdListFilter: [], // 后台返回的所有数据
3. 获取下拉列表的数据
// 接口返回的数据格式:
{
"code": "0",
"content": [
"M107NEC2E98BE9C95",
"M107W957309e677f9fb44",
"M107W01decce91b7b810c",
"M107N000822B49FFB",
"M107W512780e6ef2a40d7",
"M107N0008229CA2FB",
"M107NEC2E98BEAE31",
"M107Ne1acff34c9b13a88",
"M107N0008225CA5FB",
"M107N000822A89EFB",
"M107N0008224CA0FB",
"M107NC0847D2C5A72"
],
"message": "获取成功"
}
res.data.content.forEach(element => {
let obj = {
label: element,
value: element,
showItem: element
}
this.deviceIdList.push(obj);
this.deviceIdListFilter.push(obj);
});
4. 筛选方法以及设置高亮方法
// 自定义筛选方法
dataFilter(val) {
if (val) {
let filterResult = [];
let originalData = JSON.parse(JSON.stringify(this.deviceIdListFilter));
originalData.filter((item) => {
if (item.label.includes(val) || item.label.toUpperCase().includes(val.toUpperCase())) {
filterResult.push(item);
}
})
this.setHighlight(filterResult, val) // 匹配文字高亮显示
} else {
this.deviceIdList = this.deviceIdListFilter;
}
},
// 设置文字高亮
setHighlight(arr, keyword) {
if (arr && arr.length > 0 && keyword) {
this.deviceIdList = [];
arr.filter((item) => {
let reg = new RegExp(keyword, 'g');
let replaceString = `<span style="color:#1292FF;font-weight: bold;">${keyword.trim()}</span>`;
if (reg.test(item.label)) {
item.showItem = item.label.replace(reg, replaceString);
this.deviceIdList.push(item);
}
})
} else {
this.deviceIdList = [];
}
},
// 当下拉框出现时触发
visibleHideSelectInput(val) {
if(val) {
this.deviceIdList = JSON.parse(JSON.stringify(this.deviceIdListFilter));
}
},
以上就实现了简单的关键字高亮的下拉搜索效果~~~