el-select远程搜索时数据量过大会造成卡顿问题,因此借鉴了几篇博客,写了一个比较鸡贼的解决方法
通过自定义懒加载指令,检测滚动条的位置,当他滑到最底部时调用方法,对数据进行切割展示;
参考链接:
下面附上代码
模板区域:
<template>
<div>
<el-select
v-model="value"
filterable
remote
clearable
reserve-keyword
placeholder="请输入关键词"
:remote-method="remoteMethod"
:loading="loading"
v-el-select-loadmore="loadmore"
>
<el-option
v-for="item in options"
:key="item.id"
:label="item.label"
:value="item.id">
</el-option>
</el-select>
</div>
</template>
数据区域:
data() {
return {
value:'',
// 总列表
eventList:[],
// 下拉框中展示的列表
options: [],
// 当前搜索框内容
content:'',
// 当前展示多少条
count:50,
loading: false,
}
},
自定义指令:
// 自定义指令
directives: {
'el-select-loadmore': {
bind(el, binding) {
// 获取element-ui定义好的scroll盒子
const SELECTWRAP_DOM = el.querySelector('.el-select-dropdown .el-select-dropdown__wrap');
SELECTWRAP_DOM.addEventListener('scroll', function () {
//滚动条最底部有空隙,将底部空隙长度保存下来放在判断条件中,以解决出现滚动条永远无法真正到达底部的问题
let declare = 2
const condition = this.scrollHeight - this.scrollTop <= this.clientHeight+declare;
// 检测滚动条是否到底
if (condition) {
declare = this.scrollHeight - this.scrollTop-this.clientHeight
binding.value();
}
});
}
}
},
懒加载方法:
//滚动条滑到底部时调用
loadmore() {
// 数据个数新增50
this.count+=50
this.options = this.eventList.splice(0,this.count)
}, // 搜索框输入事件,只有在搜索框进行输入时才会调用
remoteMethod(query) {
// 保存当前搜索框内容
this.content = query
// 重置下拉框数据个数
this.count = 50
if (query !== '') {
this.loading = true
// 数据请求
数据请求方法({
query:query
}).then(res=>{
this.loading = false
// 获取所有数据并保存
this.eventList = res.data
// 列出前五十个
this.options = this.eventList.splice(0,50)
})
} else {
this.options = [];
}
},