背景
项目中遇到这种情况:当下拉数据有上千条时,编辑会卡顿缓慢,为了优化体验,使用了 下拉滚动加载 的方式:默认初始加载第一页数据,当滚动条拉到底部时,去加载下一页数据进行累加。
实现方法
首先自定义个指令selectLoadMore
Vue.directive('selectLoadMore', {
bind(el, binding){
const selectDom = el.querySelector('.el-select-dropdown .el-select-dropdown__wrap');
if (!selectDom) {
return;
}
selectDom.addEventListener('scroll', ()=>{
const height = this.scrollHeight - Math.ceil(this.scrollTop) <= this.clientHeight
if (height && this.scrollTop !== 0) {
binding.value()
}
})
}
})
HTML:
<el-select
v-model="selectId"
filterable
remote
:remote-method="(query)=>remoteMethod(query,'remote')"
@focus="focus"
@blur="query=''"
v-selectLoadMore="()=>selectLoadMore()">
<el-option
v-for="item in list"
:key="item.id"
:label="item.label"
:value="item.value">
</el-option>
</el-select>
js:
export default {
computed: {},
data() {
return {
selectId: '',
query: '', // 记录搜索输入内容,用于下拉滚动时,同步搜索条件
list: [],
currentPage: 1,
pageSize: 20,
total: 0
}
},
mounted(){
this.remoteMethod()
},
methods: {
async remoteMethod(query, type){
// 远端搜索
if (type == 'remote') {
this.query = query || ''
this.currentPage = 1;
this.total = 0;
this.list = []
} else if (type == 'scroll') {
// 滚动搜索
} else {
// 初次加载
this.currentPage = 1;
this.total = 0;
this.list = []
}
const res = await queryData({
currentPage: this.currentPage,
pageSize: this.pageSize,
name: this.query || ''
})
if (res.code == 200) {
this.list = this.list.concat(res.data.list)
}
// 初次搜索和远端搜索,需要重置总数
if (!type || type == 'remote') {
this.total = res.data.pagination.total
}
},
// 聚焦时,重新搜索首页数据
focus(){
this.remoteMethod()
},
// 滚动条-触底加载下一页
selectLoadMore(){
// 如果超出最大页码,停止
if (Math.ceil(this.total / this,pageSize) == this.currentPage) {
return;
}
this.currentPage += 1
this.remoteMethod(this.query, 'scroll')
},
}
}
哈哈,技能+1