vue - 虚拟列表实现

<template>
  <div class="scroll-main" @scroll="fn" ref="scrollBox">
    <div :style="{paddingTop:startNum * itemHeight + 'px',paddingBottom:(allHX.length  - endNum) * itemHeight + 'px'}">
      <div v-for="(item, index) in showHX" :key="item.id" class="item" :style="{height: (itemHeight - 2) + 'px'}">
        <span>{{item.id}}-{{item.msg}}</span>
        <span @click="deleteItem(index)">删除</span>
      </div>
    </div>
  </div>
</template>
<script>
export default {
  data () {
    return {
      allHX: [],
      startNum: 0,
      boxHeight: 0,
      fn: this.debounce(this.startScroll, 100),
      wishList: ['洗脚', '按摩', '给零花钱', '做饭', '买车', '买房', '做项目', '带娃', '应付丈母娘']
    };
  },
  props: {
    itemHeight: {
      type: String,
      default: '100'
    }
  },
  created () {
    this.getMock(100000);
  },
  mounted () {
    this.getBoxHeight();
  },
  methods: {
    getMock (count) {
      for (let i = 0; i < count; i++) {
        this.allHX.push({
          id: `${i}`,
          msg: `${this.wishList[i % 9]}`,
        });
      }
    },
    getBoxHeight () {
      // 获取可视区域的高度
      this.boxHeight = Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);
    },
    startScroll () {
      let target = Math.floor(this.$refs.scrollBox.scrollTop / this.itemHeight);
      if (target > this.allHX.length - this.pageNum) {
        this.startNum = this.allHX.length - this.pageNum;
        return
      }
      this.startNum = target;
    },
    deleteItem (index) {
      this.allHX.splice(this.startNum + index, 1);
    },
    debounce (fun, wait) {
      let timer = null;
      return function () {
        if (timer !== null) clearTimeout(timer);
        timer = setTimeout(fun, wait);
      }
    }
  },
  computed: {
    pageNum () {
      return Math.ceil(this.boxHeight / this.itemHeight);
    },
    endNum () {
      return this.startNum + this.pageNum;
    },
    showHX () {
      return this.allHX.slice(this.startNum, this.endNum);
    }
  }
};
</script>
 
<style scoped>
.scroll-main {
  height: 100%;
  overflow: scroll;
  overflow-x: hidden;
}
.item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border: 1px solid red;
  padding: 0 20px;
}
</style>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值