el-select下拉加载(实现懒加载)自定义loadmore事件

使用场景:下拉框远程搜索数据量较大,导致dom渲染很慢,所以远程搜索要采用分页的形式,故自定义事件,实现滚动加载,具体如下:

1、自定义事件

创建directives.js,内部实现loadmore事件,代码如下:

import Vue from 'vue'

Vue.directive('loadmore', {
  bind (el, binding) {
    // 获取element-ui定义好的scroll盒子
    const SELECTWRAP_DOM = el.querySelector('.el-select-dropdown .el-select-dropdown__wrap');
    SELECTWRAP_DOM.addEventListener('scroll', function () {
      const CONDITION = this.scrollHeight - this.scrollTop <= this.clientHeight;
      if (CONDITION) {
        binding.value()
      }
    })
  }
})

main.js全局引用
import ‘@/util/directives.js’

2、组件中使用代码

<el-select
              class="roleSelect"
              v-model="item.roleId"
              v-loadmore="loadMoreFun"
              filterable
              remote
              :remote-method="getActorRole"
              @change="getRole($event,index)"
              placeholder="请搜索..."
            >
              <el-option
                v-for="item in roleList"
                :key="item.roleId"
                :label="item.roleName"
                :value="item.roleId"
              ></el-option>
            </el-select>
/**
     * 鼠标滚动加载
     */
    loadMoreFun() {
      this.page++;
      this.getActorRole(this.query)
    },
    // 获取所有角色
    getActorRole (query) {
      let timer;
      if (timer) {
        clearTimeout(timer)
      }
      timer = setTimeout(() => {
        if (query !== '') {
          if (query !== this.query) {
            this.page = 1;
            this.roleList = [];
            this.query = query;
          }
          let param = {
            page: this.page,
            rows: 20,
            sidx: "roleId",
            sord: "desc",
            roleName: query
          };
          get_role_query_roles(param).then(data => {
            if (data.code == '0') {
              if (data.result && data.result.length) {
                this.roleList = [...this.roleList, ...data.result];
              }
            }
          }).catch(() => {
            this.$openMessage('查询失败', "error");
          })
        }
      }, 300);
    },

参考博客:https://www.cnblogs.com/wangxiaoer5200/p/10922005.html

Logo

前往低代码交流专区

更多推荐