Element 自定义指令 下拉分页,获取无限数据

template 代码

  <el-form-item>
    <el-select
      v-model="form.batchId"
      v-loadmore="loadmoreBatchList"
      placeholder="请输入批次名称"
      filterable
      clearable>
        <el-option v-for="(item, key) in batchList.list" :key="key" :label="item.batchName" :value="item.id"></el-option>
    </el-select>
  </el-form-item>

data 下拉数据:

   batchList: {
    list: [],
    total: 0,
    pageNo: 1,
    pageSize: 100
   },

methods 方法:

import { uniqBy } from 'lodash'

    loadmoreBatchList() {
      if (this.batchList.total > this.batchList.list.length) {
        this.getBatchList(data, ++this.batchList.pageNo)
      }
    },

    getBatchList(data, pageNo = 1) {
      // data 为接口传递的自定义数据
      this.$store.dispatch('getOutboundBatchsList', {
        ...data,
        pageNo: pageNo,
        pageSize: this.batchList.pageSize
      })
        .then(({ code = 0, data = {} }) => {
          if (code == 1 && data.total) {
            this.batchList = {
              ...this.batchList,
              list: uniqBy([...this.batchList.list, ...data.list], 'id'),
              total: data.total
            }
          }
        })
    },

loadmore 自定义指令

Vue.directive('loadmore', {
  bind(el, binding) {
    // 获取element-ui定义好的scroll盒子
    const SELECTWRAP_DOM = el.querySelector(
      '.el-select-dropdown .el-select-dropdown__wrap'
    )
    if (SELECTWRAP_DOM) {
      SELECTWRAP_DOM.addEventListener('scroll', function() {
        /*
         * scrollHeight 获取元素内容高度(只读)
         * scrollTop 获取或者设置元素的偏移值,常用于, 计算滚动条的位置, 当一个元素的容器没有产生垂直方向的滚动条, 那它的scrollTop的值默认为0.
         * clientHeight 读取元素的可见高度(只读)
         * 如果元素滚动到底, 下面等式返回true, 没有则返回false:
         * ele.scrollHeight - ele.scrollTop === ele.clientHeight;
         */
        const CONDITION =
          this.scrollHeight - this.scrollTop - 1 <= this.clientHeight
        if (CONDITION) {
          console.log('----------------------------')
          console.log('loadmore', CONDITION)
          console.log('scrollHeight', this.scrollHeight)
          console.log('scrollTop', this.scrollTop)
          console.log('clientHeight', this.clientHeight)
          console.log('----------------------------')
          binding.value()
        }
      })
    }
  }
})
posted @ 2023-07-05 11:10  DL·Coder  阅读(39)  评论(0编辑  收藏  举报