下拉框里数据过多,一次性请求接口响应有点慢,这时候我们可以对数据进行分页加载
先在main.js里注册一个全局指令,用于监听下拉框是否触底
Vue.directive('selectLoadMore', {
bind (el, binding) {
// 获取element-ui定义好的scroll盒子
const selectDom = el.querySelector('.el-select-dropdown .el-select-dropdown__wrap')
selectDom .addEventListener('scroll', function () {
if (this.scrollHeight - this.scrollTop < this.clientHeight + 1) {
binding.value()
}
})
}
})
封装一个下拉框分页的组件,支持远程搜索
<template>
<div>
<el-select
v-model="selectValue"
clearable
filterable
v-selectLoadMore="selectLoadMore"
:loading="loading"
remote
:remote-method="remoteMethod"
@clear="clearClick"
placeholder="请选择"
>
<el-option
v-for="item in list"
:key="item.id"
:label="item.name"
:value="item.id"
>
</el-option>
</el-select>
</div>
</template>
<script>
export default {
data () {
return {
selectValue: '',
loading: false,
search: {
name: ''
start: 1,
limit: 10
},
total: 0,
list: []
}
},
created () {
this.getList()
},
methods: {
// 下拉加载更多
selectLoadMore () {
console.log('触底了')
this.search.start = this.search.start + 10
if (this.search.start > this.total) return
this.getList()
},
// 远程搜索
remoteMethod (val) {
console.log('输入了', val)
this.loading = true
this.search.name = val
this.search.start = 1
this.list= []
setTimeout(() => {
this.loading = false
this.getList()
}, 500)
},
// 获取数据
getList() {
managePaginate(this.search).then(res => {
this.total = res.result.total
this.list= this.list.concat(res.result.records)
})
},
// 输入框清空后重新加载数据
clearClick () {
this.search.name = ''
this.search.start = 1
this.list= []
this.getList()
}
}
}
</script>
<style lang="scss" scoped></style>