添加自定义指令函数在main.js抛出,方便系统其他地方可以直接调用
// 自定义指令,监听el-autocomplete下拉框的滚动,滚动到底部就加载下一页
Vue.directive('scrollLoad', {
bind(el, binding, vnode) {
function handleScroll(e) {
let isBottom = e.target.clientHeight + e.target.scrollTop >= e.target.scrollHeight - 40
if (isBottom && !vnode.context.loading) {
binding.value()
}
}
// 监听滚动
let wrapDom = el.querySelector('.el-autocomplete-suggestion__wrap')
el.__handleScroll__ = handleScroll
el.__wrapDom__ = wrapDom
wrapDom.addEventListener('scroll', handleScroll, false)
},
unbind(el, binding, vnode) {
// 解除事件监听
el.__wrapDom__.removeEventListener('scroll', el.__handleScroll__, false)
},
})
在需要使用的地方直接使用v-scrollLoad="handleScroll"
// 调用地方
<el-autocomplete
ref="refName"
:fetch-suggestions="remoteMethod"
@select="handleSelect"
v-model="completeData"
v-scrollLoad="handleScroll"
/>
// 方法定义
handleScroll(event) {
// 添加加载loading,避免请求未完成时重复请求导致页码和数据错乱
if(this.moreLoading) {
return
}
this.moreLoading = true
this.page += 1
// getData自定义的请求数据的方法,在callback里处理下拉列表的数据
this.getData(arr=>{
this.$refs[refName].$data.suggestions.push(...arr)
this.$nextTick(()=>{
this.moreLoading = !arr.length
})
})
}