vue大数据展示之虚拟列表

 面试代码学习

 父组件:

<template>
    <div class="box">
      <!--items总条数、 size数据高度、 shownumber每次渲染数据-->
      <list :items="items" :size="60" :shownumber="10"></list>
    </div>
  </div>
</template>
<script>

import list from './list.vue'
export default {
  components: {
    list,
  },
  data() {
    return {}
  },
  computed: {
    items() {
      return Array(10000).fill('').map((item, index) => {
        return {
          id: index,
          content: '列表内容' + index
        }
      })
    }
  }
};
</script>

子组件

list.vue

<template>
    <div class="container" :style="{ height: containerHeight }" @scroll="handleScroll" ref="container">
      <!-- list 高度为 所有数据的高度  listTop 动态改变高度位置-->
      <div class="list" :style="{ top: listTop }">
        <div v-for="item in showData" :key="item.id" :style="{height: size + 'px'}">
          {{ item.content }}
        </div>
        <!-- 撑开所有元素列表高度 -->
        <div class="bar" :style="{height: barHeight}"></div>
      </div>
    </div>
  </template>
  
  <script>
  export default {
    props: {
      items: {
        type: Array,
        required: true
      },
      size: {
        type: Number,
        required: true
      },
      shownumber: {
        type: Number,
        required: true
      }
    },
    data() {
      return {
        start: 0, // 起始下标
        end: this.shownumber, // 结束下标
      }
    },
    computed: {
      // 展示数据
      showData() {
        return this.items.slice(this.start, this.end)
      },
      // 列表高度
      containerHeight() {
        return this.size * this.shownumber + 'px'
      },
      // 撑开容器高度的元素高度
      barHeight() {
        return this.size * this.items.length - this.start * this.size + 'px'
      },
      // 列表 距离顶部的距离
      listTop() {
        return this.start * this.size + 'px'
      }
    },
    methods: {
      // 滚动事件
      handleScroll() {
        // 获取滚动条距离顶部的距离
        const scrollTop = this.$refs.container.scrollTop
        // 计算卷去的数据条数,用计算的结果作为获取数据的起始和结束下标
        // 起始下标就是券去的数据条数向下取整
        this.start = Math.floor(scrollTop / this.size)
        // 结束的下标就是起始下标加上展示的条数
        this.end = Math.min(this.start + this.shownumber, this.items.length)
        console.log(this.start + '---' + this.end)
      }
    }
  }
  </script>
  
  <style scoped>
  .container {
    overflow-y: auto;
    background-color: rgba(255, 255, 255, 0.5);
    font-size: 20px;
    font-weight: bold;
    line-height: 60px;
    width: 500px;
    margin: 0 auto;
    position: relative;
    text-align: center;
  }
  .list {
    position: absolute;
    top: 0;
    width: 100%;
  }
  </style>

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值