vxe-list做列表虚拟滚动时,底部间距的优化

发布于:2024-07-02 ⋅ 阅读:(19) ⋅ 点赞:(0)

已知vxe-list在数据超出一定行时会自动启用纵向虚拟滚动配置,默认效果如图:

但是在滚动中我们发现有时列表底部间距不一致,而且会出现在感官上底部空白过多的情况:

这时候我们想让列表恰好显示完全应该怎么做呢,查看官网的api发现,在Methods属性中有一个scrollTo方法能手动控制列表的滚动距离,这样当列表滚动时判断如果不能恰好显示完全我们就手动控制偏移到恰好的距离:

具体代码如下:

<template>
  <div>
    <div class="my-select">
      <input type="text" class="my-select-input" />
      <vxe-list class="my-select-wrapper" :loading="loading" :data="list" height="200" :scroll-y="vScrollY" ref="vxeList" @scroll="scroll">
        <template v-slot="{ items }">
          <div class="my-select-option" v-for="item in items" :key="item.value">
            {{ item.label }}
          </div>
        </template>
      </vxe-list>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      loading: false,
      list: [],
      vScrollY:{oSize:1},//除计算显示出的几行外,多渲染n行,滚动时多会显示2n行
      interval:null,
      itemHeight:24,//单行高度
    }
  },
  created() {
    this.loading = true;
    setTimeout(() => {
      const startTime = Date.now();
      var list = [];
      for (var i = 0; i < 1000; i++) {
        list.push({ label: "选项" + i, value: i });
      }
      this.list = list;
      this.loading = false;
    }, 200);
  },
  methods:{
    loadData(data){
      console.log('data',data)
    },
    clearScroll(){
      this.$refs.vxeList.clearScroll();
    },
    recalculate(){
      this.$refs.vxeList.recalculate();
    },
    scroll(e){
      if(this.interval){
        clearTimeout(this.interval);
        this.interval = setTimeout(()=>{
          this.interval = null
          if(e.scrollTop%this.itemHeight!=0){
            let top = Math.floor(Number(e.scrollTop)/this.itemHeight)*this.itemHeight+this.itemHeight;
            console.log('top',top)
            this.$refs.vxeList.scrollTo(0,top);
          }
        },50)
      }else{
        this.interval = setTimeout(()=>{
          this.interval = null
          if(e.scrollTop%this.itemHeight!=0){
            let top = Math.floor(Number(e.scrollTop)/this.itemHeight)*this.itemHeight+this.itemHeight;
            console.log('top',top)
            this.$refs.vxeList.scrollTo(0,top);
          }
        },50)
      }
      
    },
    scrollTo(){
      this.$refs.vxeList.scrollTo(0,500);
    }
  }
};
</script>
<style lang="less" scoped>
.my-select {
  width: 200px;
  position: relative;
  background-color: #fff;
}
.my-select-input {
  width: 100%;
  height: 24px;
  border: 1px solid #dcdfe6;
}
.my-select-wrapper {
  position: absolute;
  left: 0;
  top: 26px;
  width: 100%;
  height: 200px;
  background-color: #fff;
  border: 1px solid #dcdfe6;
}
.my-select-option:hover {
  background-color: #f5f7fa;
  cursor: pointer;
}
.my-select-option{
  line-height: 24px;
}
/deep/ .vxe-list--virtual-wrapper{
  height: 200px;
}
/deep/ .my-select-wrapper{
  overflow: hidden;
}
</style>

文章参考:vxe-list vue 如何实现下拉框的虚拟列表_vue.js_脚本之家