Vue + Element 下拉框远程搜索回显
程序员文章站
2023-12-27 15:56:03
...
<template>
<el-select
ref="selectDom"
v-model="ids"
multiple
filterable
placeholder="请输入关键词"
remote
:remote-method="remoteMethod"
@visible-change="visibleChange"
>
<el-option
v-for="item in options"
:key="item.id"
:label="item.name"
:value="item.id"
>
</el-option>
</el-select>
</template>
<script>
export default {
data() {
return {
ids: [1, 15],
options: [],
list: [],
};
},
mounted() {
this.init();
},
methods: {
init() {
// 数据源
this.list = [
{ name: "Alabama", id: 1 },
{ name: "Alaska", id: 2 },
{ name: "Pennsylvania", id: 3 },
{ name: "Rhode Island", id: 4 },
{ name: "South Carolina", id: 5 },
{ name: "South Dakota", id: 6 },
{ name: "Tennessee", id: 7 },
{ name: "Texas", id: 8 },
{ name: "Utah", id: 9 },
{ name: "Vermont", id: 10 },
{ name: "Virginia", id: 11 },
{ name: "Washington", id: 12 },
{ name: "West Virginia", id: 13 },
{ name: "Wisconsin", id: 14 },
{ name: "Wyoming", id: 15 },
];
// 默认展示10条
this.options = this.list.slice(0, 10);
// 解决回显时显示为id的问题
this.list.forEach((item) => {
this.$refs["selectDom"].cachedOptions.push({
currentLabel: item.name,
currentValue: item.id,
label: item.name,
value: item.id,
});
});
},
remoteMethod(query) {
if (query !== "") {
// 展示匹配的前10条
this.options = this.list
.filter((item) => {
return item.name.toLowerCase().indexOf(query.toLowerCase()) > -1;
})
.slice(0, 10);
} else {
// 展示10条
this.options = this.list.slice(0, 10);
}
},
visibleChange(value) {
if (!value) {
// 展示10条
this.options = this.list.slice(0, 10);
}
},
},
};
</script>