vue3 elementUI select 下拉加载更多(最新-组件封装)
<template>
<el-select
v-model="selectedValue"
filterable
remote
:remote-method="remoteMethod"
:loading="loading"
@change="handleChange"
placeholder="请选择"
>
<el-option
v-for="item in options"
:key="item.value"
:label="item.label"
:value="item.value"
></el-option>
<el-pagination
v-if="total > pageSize"
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
:current-page.sync="currentPage"
:page-size="pageSize"
:total="total"
layout="prev, pager, next"
class="pagination"
></el-pagination>
</el-select>
</template>
<script>
export default {
props: {
// 初始选中值
value: [String, Number],
// 获取数据的方法
fetchDataMethod: {
type: Function,
default: () => Promise.resolve({ data: [], total: 0 })
},
// 每页条数
pageSize: {
type: Number,
default: 10
}
},
data() {
return {
selectedValue: this.value,
options: [],
currentPage: 1,
total: 0,
loading: false
};
},
watch: {
value(newValue) {
this.selectedValue = newValue;
},
selectedValue(newValue) {
this.$emit('update:value', newValue);
}
},
created() {
this.fetchData();
},
methods: {
async fetchData() {
this.loading = true;
try {
const { data, total } = await this.fetchDataMethod({ page: this.currentPage, pageSize: this.pageSize });
this.options = data;
this.total = total;
} catch (error) {
console.error('Error fetching data:', error);
} finally {
this.loading = false;
}
},
remoteMethod(query) {
if (query !== '') {
this.currentPage = 1;
this.fetchData();
} else {
this.options = [];
}
},
handleSizeChange(newSize) {
this.pageSize = newSize;
this.fetchData();
},
handleCurrentChange(newPage) {
this.currentPage = newPage;
this.fetchData();
},
handleChange(value) {
this.$emit('change', value);
}
}
};
</script>
这个代码示例展示了如何在Vue 3中使用Element UI的<el-select>
组件来创建一个支持下拉加载更多数据的选择器。它使用filterable
和remote
属性来启用远程搜索,并且使用el-pagination
组件来处理分页。代码中包含了加载数据的逻辑和错误处理,并且可以通过props来接收外部的数据和方法。
评论已关闭