中使用Element UI的el-select组件实现下滑分页加载的功能,通过自定义指令来判断是否需要滚动加载下一页数据

<template>
  <el-select
    v-model="selectedValue"
    filterable
    :filter-method="(value)=>{remoteMethod(value)}"
    v-el-select-loadmore="loadMore"
    @focus="remoteMethod('')"
  >
    <el-option
      v-for="(option,index) in options"
      :key="index"
      :label="option.label"
      :value="option.value"
    ></el-option>
  </el-select>
</template>
 
<script>
export default {
  name:'mySelect',
  data() {
    return {
      selectedValue: null,
      options: [],
      page: 1,
      pageSize: 10,
      total: 100,//假设总共有100条数据
      stopLoading:false,//最后一次加载之后,不再加载
      query:''//可输入值搜索
    };
  },
  methods: {
    remoteMethod(query){
      if(typeof query === 'string'){
          this.querys = query;
      }else{
          this.querys = '';
      }
      this.loadOptions();
    },
    loadOptions() {
      //如果需要搜索参数可带入参数this.querys
      // 模拟异步加载数据
      setTimeout(() => {
        const start = (this.page - 1) * this.pageSize;
        const end = start + this.pageSize;
        let array = Array.from({ length: this.total }, (_, i) => ({
          value: i + 1,
          label: `Option ${i + 1}`,
        })).slice(start, end);
        if(this.page == 1){
          this.options = array
        }else{
          this.options = [...this.options,...array];
        }
        if(this.options.length == this.total){
          this.stopLoading = true;
        }
      }, 500);
    },
    loadMore() {
      if (!this.stopLoading) {
        this.page += 1;
        this.loadOptions();
      }
    }
  },
  created() {
    this.loadOptions();
  },
  directives: {
    'el-select-loadmore': {
        bind(el, binding) {
            // 下拉框下拉的框
            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();
                }
            });
        }
    }
},
};
</script>
GitHub 加速计划 / eleme / element
54.06 K
14.63 K
下载
A Vue.js 2.0 UI Toolkit for Web
最近提交(Master分支:3 个月前 )
c345bb45 7 个月前
a07f3a59 * Update transition.md * Update table.md * Update transition.md * Update table.md * Update transition.md * Update table.md * Update table.md * Update transition.md * Update popover.md 7 个月前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐