一:需求
element-ui的el-select下拉更多和远程搜索
https://element.eleme.cn/#/zh-CN/component/select#methods
二:工具类的封装
class Pages {
constructor(options = {}) {
this.options = {
page: 0,
pageSize: 10,
hasNext: true,
total: 0,
fetch: () => {},
...options
}
return this
}
setTotal(total) {
this.options.total = total
if (Math.ceil(total / this.options.pageSize) <= this.options.page) {
this.options.hasNext = false
}
}
setPage(page) {
this.options.page = page
// this.options.fetch({ page: this.options.page, pageSize: this.options.pageSize })
}
reset() {
this.options.page = 1
this.options.total = 0
this.options.hasNext = true
console.log(123,this)
this.options.fetch({ page: this.options.page, pageSize: this.options.pageSize }, ...arguments)
}
refresh() {
this.options.fetch({ page: this.options.page, pageSize: this.options.pageSize })
}
nextPage() {
const { hasNext, fetch, pageSize } = this.options
this.options.page++
if (hasNext) {
fetch({ page: this.options.page, pageSize }, ...arguments)
}
return this
}
}
export default Pages
三:自定义滑动指令封装
import Vue from 'vue'
export default () => {
Vue.directive('scroll', {
bind (el, binding) {
let SCROLL_DOM = el.querySelector('.el-select-dropdown .el-select-dropdown__wrap')
SCROLL_DOM.addEventListener('scroll', function () {
const scrollDistance = this.scrollHeight - this.scrollTop - this.clientHeight
if (scrollDistance === 0) {
binding.value(true)
}
})
}
})
}
四:业务代码实现
<template>
<el-select
v-model="ddForm.distributor_id"
v-scroll="() => this.pageQuery.nextPage()"
clearable
@clear="() => this.onRemoteGetMerchant()"
@focus="() => this.onRemoteGetMerchant()"
filterable
:loading="remoteLoading" remote
:remoteMethod="(e) => this.onRemoteGetMerchant(e)"
>
<el-option
v-for="(item, index) in distributorList"
:key="`option-item__${index}`"
:label="item.title"
:value="item.value" />
</el-select>
</template>
//data省略
created() {
this.pageQuery = new Pages({
pageSize: 10,
fetch: this.getDistributorList
}).nextPage()
}
methods: {
onRemoteGetMerchant(e) {
this.distributorList = []
this.pageQuery.reset(e)
},
async getDistributorList({ page, pageSize }, keywords) {
let params = {
pageSize,
page
}
if (!isEmpty(keywords)) {
params = {
...params,
name: keywords
}
}
if (page == 1) {
this.remoteLoading = true
}
const { list, total_count } = await this.$api.member.getMemberDistributor(params)
if (page == 1) {
this.remoteLoading = false
}
this.pageQuery.setTotal(total_count)
this.distributorList = this.distributorList.concat(
list.map((k) => {
return {
title: `【${k.shop_code}】${k.name}`,
value: k.distributor_id
}
})
)
},
注:el-select中使用箭头函数,因为remoteMethod需要传e,获取到输入的值,而其他两个无需传e, @focus=“onRemoteGetMerchant” 这样写,focous时会打印keywords是e!注意此写法!