当初始化时el-select数据量过大存在卡顿问题,可以通过触底刷新的方式实现分页获取。通过自定义内置指令,可以在项目中进行多处使用,更友好。
1,新建loadMore.js在公共方法中(通过注释中稍加调整,块元素触底刷新同样适用)
import Vue from 'vue'
Vue.directive('load-more', {
bind(el, binding) {
let value = ''
el.addEventListener('input', function() {
value = el.querySelector('.el-select__input').value
})
// 获取滚动页面DOM
const SCROLL_DOM = el.querySelector('.el-select-dropdown .el-select-dropdown__wrap')
let scrollPosition = 0
//el.addEventListener可直接对当前dom元素进行滚动监听,实现当前dom元素的触底刷新功能
SCROLL_DOM.addEventListener('scroll', function() {
// 当前的滚动位置 减去 上一次的滚动位置
// 如果为true则代表向上滚动,false代表向下滚动
const flag = this.scrollTop - scrollPosition > 0
// 记录当前的滚动位置
scrollPosition = this.scrollTop
// 记录滚动位置距离底部的位置,在滚动位置距离滚动页面底部一定高度时在触发,例如距页面底部只有100px时触发loadMore事件
const LIMIT_HEIGHT = 10
const scrollBottom = this.scrollHeight - (this.scrollTop + this.clientHeight) < LIMIT_HEIGHT
const { loadMore } = binding.value
// 如果已达到指定位置则触发
// 如果向下滚动 并且距离底部只有10px
if (flag && scrollBottom) {
// 将滚动行为告诉组件
loadMore(true, value)
}
// 如果是向上滚动 并且距离顶部只有100px
// if (!flag&& this.scrollTop < LIMIT_HEIGHT) {
// loadMore(flagToDirection, value)
// }
})
}
})
2,在页面中使用该自定义指令
<el-select
v-model="temp.userId"
multiple
placeholder="选择用户"
filterable
v-load-more="{ loadMore }"
>
<el-option
v-for="item in userList"
:key="item.id"
:label="item.name"
:value="item.id"
/>
</el-select>
3,通过自定义指令调用数据请求实现加载更多
// 触底刷新
loadMore(flag, value) {
flag && this.getUserList(++this.pageIndex)
},
//调用获取数据
getUserList(pageIndex = 1, pageSize = 20) {
if (this.userList.length === this.userTotal&&this.pageIndex!==1) return
this.pageIndex = pageIndex
getUserList({ pageNum: this.pageIndex, pageSize }).then((response) => {
if (this.pageIndex === 1) this.userList = response.data.records
else this.userList = this.userList.concat(response.data.records)
this.userTotal= response.data.total
})
},