在项目中经常会用到el-select远程所搜,今天记录一下
1.首先将组件引入到项目页面中
<el-select
v-model="ruleForm.newCertificateName"
filterable
remote
reserve-keyword
:remote-method="remoteMethod"
clearable
placeholder="请选择新证书名称"
@change="changeVal"
>
<el-option
v-for="item in options"
:key="item.value"
:label="item.label"
:value="item"
>
</el-option>
</el-select>
filterable:是否可搜索
remote:是否远程搜索
remote-method:远程搜索的方法
change:选中值发生变化触发
options:下拉框内容
2.在data中定义options和list
data() {
return {
list: [],//输入值过滤的内容
options: [],//下拉框内容
},
}
3.调用后端接口获取值
getGood() {
getAllGoodsApi().then((res) => {
if (res.code == 0) {
// console.log(res);
// 将返回结果的data字段proId,proName映射到数组list中
this.list = res.data.map((item) => {
return { value: `${item.proId}`, label: `${item.proName}` };
});
}
});
},
4.根据输入的值过滤
// 根据输入的值过滤
remoteMethod(query) {
// console.log(query);
// console.log(this.list, 1);
if (query !== "") {
//根据输入的值过滤list数组,并将结果赋值给options,用于展示下拉选型
this.options = this.list.filter((item) => {
return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1;
});
} else {
// 当query为空时option为空数组
this.options = [];
}
},
5.选择的项
changeVal(val) {
// console.log(val);
this.ruleForm.newCertificateName = val.label;
},