写一个vue+element selected远程搜索下拉框虚拟列表
时间: 2024-01-13 15:06:00 浏览: 122
使用 Vue 实现一个虚拟列表的方法
以下是一个基本的Vue Element远程搜索下拉框虚拟列表组件。此组件包括以下功能:
- 支持远程搜索
- 支持虚拟滚动
- 支持选中项
```html
<template>
<el-select
v-model="selected"
filterable
remote
reserve-keyword
remote-method="remoteMethod"
:loading="loading"
:options="options"
popper-class="virtual-list-popper"
class="virtual-list-select"
>
<template #default="{option}">
<div class="virtual-list-item">{{ option.label }}</div>
</template>
</el-select>
</template>
<script>
export default {
name: "VirtualListSelect",
data() {
return {
loading: false,
options: [],
selected: null,
pageSize: 50,
pageNum: 1,
total: 0,
keyword: "",
};
},
methods: {
async remoteMethod(keyword) {
this.loading = true;
this.keyword = keyword;
this.pageNum = 1;
await this.loadData();
this.loading = false;
},
async loadData() {
const { data } = await this.fetchData();
this.options = data;
this.total = data.length;
},
async fetchData() {
const start = (this.pageNum - 1) * this.pageSize;
const end = start + this.pageSize;
const response = await fetch(
`https://api.example.com/search?q=${this.keyword}&start=${start}&end=${end}`
);
const json = await response.json();
return json;
},
handleScrollToEnd() {
if (this.options.length < this.total) {
this.pageNum++;
this.loadMoreData();
}
},
async loadMoreData() {
const { data } = await this.fetchData();
this.options.push(...data);
},
},
mounted() {
const popper = document.querySelector(".virtual-list-popper");
popper.addEventListener("scroll", () => {
const scrollTop = popper.scrollTop;
const scrollHeight = popper.scrollHeight;
const clientHeight = popper.clientHeight;
if (scrollHeight - scrollTop === clientHeight) {
this.handleScrollToEnd();
}
});
},
};
</script>
<style>
.virtual-list-select .el-input__suffix {
right: 10px;
}
.virtual-list-item {
height: 50px;
line-height: 50px;
padding: 0 20px;
border-bottom: 1px solid #ebeef5;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.virtual-list-popper {
max-height: 300px;
overflow-y: auto;
}
</style>
```
使用示例:
```html
<virtual-list-select />
```
阅读全文