vue虚拟列表展示

效果图

在这里插入图片描述
在这里插入图片描述


<template>
  <!-- 总体高度区域 -->
  <div
    ref="listWrap"
    class="m-container"
    @scroll="scrollListener"
  >
    <div
      :style="handleContainerHeight()"
    >
      <!-- 可视区域 -->
      <div
        class="m-area"
        :style="handleAreaStyle()"
      >
        <div
          v-for="(item,index) in displayList"
          :key="index"
          :style="handleItemStyle()"
        >
          {{ item.name }}
        </div>
      </div>
    </div>
  </div>
</template>
<script lang="ts">
import { Options, Vue } from 'vue-class-component';
interface ListType {
  label: string;
  value: string;
}
@Options({
  props: {
    list: {
      default:[],
    },
  },
})
export default class MList extends Vue {
  list!: ListType[];
  /** 每行高度 */
  itemSize = 100;
  /** 一次性展示多少个数据 */
  showNum = 10;
  /** 开始下标 */
  start =0;
  /** 结束下标 */
  end = 10;
  /** 滚动位置 */
  scrollTop = 0;

  get displayList() {
    const arr = this.list.slice(this.start,this.end);
    if(arr.length) {
      return arr;
    }

    return [];
  }

  handleItemStyle() {
    return {
      height: `${this.itemSize}px`,
    };
  }

  handleContainerHeight() {
    return {
      height: this.list.length * this.itemSize + 'px',
    };
  }

  handleAreaStyle() {
    return {
      'transform': `translateY(${this.scrollTop}px)`,
    };
  }

  scrollListener() {
    this.scrollTop = (this.$refs.listWrap.scrollTop as number);
    this.start = Math.floor(this.scrollTop/this.itemSize);
    this.end = this.start + this.showNum;
  }

}
</script>
<style scoped>
.m-container {
  height: 100vh;
  overflow: auto;
}
</style>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值