element-ui select 组件上拉加载更多数据

场景描述:下拉框的选项很多,上万个选项甚至更多;如果把全部把数据放到下拉框中渲染出来,浏览器会卡死,体验会特别的不好。

在 element-ui 官网中,并没有提供 select 组件下拉滚动滚动条加载更多数据的事件,可以我们想到在数据的底部添加一个点击事件来加载更多数据,但是交互就没有那么友好了。

设置高度,当超过一个高度在加载一页数据,即实现加载更多数据。

// 针对 el-select 下拉框定义的一个分页指令:滚动到底部执行加载下一页
const selectLoadMore = Vue.directive('selectLoadMore',{
  bind (el, binding) {
    // 获取element-ui定义好的scroll盒子
    const SELECTWRAP_DOM = el.querySelector('.el-select-dropdown .el-select-dropdown__wrap')
    SELECTWRAP_DOM.addEventListener('scroll', function () {
      if (this.scrollHeight - this.scrollTop < this.clientHeight + 1) {
        binding.value()
      }
    })
  }
})
export { selectLoadMore }

在 select 组件中,添加指令。

<el-select
  class="wd"
  size="small"
  v-model="baseForm.goodsName"
  placeholder="请选择"
  value-key="itemCode"
  filterable
  remote
  v-selectLoadMore="selectLoadMore"
  :loading="loading"
  :remote-method="remoteMethod"
>
  <el-option
    v-for="item in goodsCategoryData"
    :key="item.id"
    :label="item.goodsName"
    :value="item.goodsName"
  />
</el-select>

select 下拉加载更多

selectLoadMore () {
  this.pageData.currentNo = this.pageData.currentNo + 1
  if (this.pageData.currentNo > this.pageData.pageCount) {
    return
  }
  this.getGoodsList() // 请求接口
},

远程搜索方法

remoteMethod (query) {
  this.pageData.quickQuery = query
  this.pageData.currentNo = 1
  this.goodsCategoryData = []
  this.loading = true
  setTimeout(() => {
    this.loading = false
    // 查询数据
    this.getGoodsList()
  }, 200)
},

接口请求参数:

async getGoodsList () {
  const param = {
    current: this.pageData.currentNo,
    size: this.pageData.pageSize,
    itemCode: this.detailObject.itemCode,
    goodsName: this.pageData.quickQuery,
  }
  const resp = await common.getGoodsList(param)
  this.goodsCategoryData = [...this.goodsCategoryData, ...resp.data.rows]
  const { currentNo, pageCount, total } = resp.data
  this.pageData = {
    ...this.pageData,
    currentNo,
    pageCount,
    total,
  }
},

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

更新

进阶版:如何将 select 组件上拉加载更多数据封装为组件呢?

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值