添加自定义指令函数在main.js抛出,方便系统其他地方可以直接调用
import '@/utils/scrollLoad'
// 自定义指令,监听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"
class="site"
suffix-icon="el-icon-search"
v-model="keyword"
:fetch-suggestions="querySearch"
@select="handleSelect"
v-scrollLoad="handleScroll"
>
<div slot-scope="{ item }" flex="cross:center box:last">
<div>{{ item.code }}({{ item.name }})</div>
<el-icon class="el-icon-position"></el-icon>
</div>
</el-autocomplete>
//data定义
data() {
return {
keyword: '',
restaurants: [],
moreLoading: false,
page: 1
}
},
// 方法定义
mounted() {
this.$nextTick(() => {
this.loadAll(arr => {
this.restaurants = arr
})
})
},
handleScroll(event) {
// 添加加载loading,避免请求未完成时重复请求导致页码和数据错乱
if(this.moreLoading) {
return
}
this.moreLoading = true
this.page += 1
// getData自定义的请求数据的方法,在callback里处理下拉列表的数据
this.loadAll(arr=>{
this.$refs[refName].$data.suggestions.push(...arr)
this.$nextTick(()=>{
this.moreLoading = !arr.length
})
})
querySearch(queryString, cb) {
console.log(queryString)
console.log(this.restaurants)
const restaurants = this.restaurants
console.log(restaurants)
const results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants
// 调用 callback 返回建议列表的数据
cb(results)
}
async loadAll(callback) {
try {
// const response = await fetch('https://example.com/api/data')
// const data = await response.json()
// if (data && Array.isArray(data)) {
// callback(data)
// }
const res = await RequestPost(SYSTEM_CONFIG.APIS.API__ATTST, {
pageNo: this.page,
pageSize: 100,
dataType: Number(this.selected),
stCode: this.keyword
})
const data = res.data.records
if (data && Array.isArray(data)) {
callback(data)
}
} catch (error) {
console.log(error)
}
},