vue实现虚拟列表滚动

csharp 复制代码
<template>
<div class="cont">
//box 视图区域Y轴滚动 滚动的是box盒子 滚动条显示的也是因为box
  <div class="box">
  //itemBox。 一个空白的盒子 计算高度为所有数据的高度 固定每一条数据高度为50px
    <div class="itemBox" :style="{height:list.length*50+'px'}">
      <div v-for="(v,i) in showList" :style='{top: `${v.top}px`}' class="item" :key="i">{{ v.name }}</div>
    </div>
  </div>
</div>
</template>
csharp 复制代码
<script>
export default {
  data() {
    return {
      list: [],   //实际数据
      showList: [],  //渲染数据
    }
  },
  methods: {
  //滚动事件 动态去截取数据塞进showList
    handleScroll() {
      let box = document.querySelector('.box')
      let scrollTop = box.scrollTop
      let num = Math.ceil(scrollTop / 50)
      let arr = this.list.slice(num, num + 20)
      arr.forEach((v, i) => {
        v.top = (num + i) * 50 //动态计算每一条数据的位置
      })
      this.showList = arr
    }
  },
  mounted() {
  //模拟生产10000条数据
    for (let i = 0; i < 10000; i++) {
      this.list.push({
        name: '测试测试测' + i,
      })
    }
    //注册滚动事件
    let box = document.querySelector('.box')
    box.addEventListener('scroll', this.handleScroll)
    //初始渲染数据
    let arr = this.list.slice(0, 20)
    arr.forEach((v, i) => {
      v.top = i * 50
    })
    this.showList = arr
  }

}
</script>
csharp 复制代码
<style lang="scss" scoped>
.box {
  width: 600px;
  height: 800px;
  overflow-y: auto;
  background-color: #eee;
  margin: 0 auto;
  .itemBox {
    position: relative;
    .item {
      height: 50px;
      line-height: 50px;
      position: absolute;
    }
  }

}
</style>



dom中始终只显示20条dom数据,只适用固定行高度的场景

相关推荐
Zha0Zhun36 分钟前
一个使用ViewBinding封装的Dialog
前端
兆子龙36 分钟前
从微信小程序 data-id 到 React 列表性能优化:少用闭包,多用 data-*
前端
滕青山37 分钟前
文本行过滤/筛选 在线工具核心JS实现
前端·javascript·vue.js
时光不负努力39 分钟前
编程常用模式集合
前端·javascript·typescript
时光不负努力40 分钟前
ts+vue3开发规范
vue.js·typescript
大雨还洅下43 分钟前
前端JS: 跨域解决
javascript
恋猫de小郭1 小时前
Apple 的 ANE 被挖掘,AI 硬件公开,宣传的 38 TOPS 居然是"数字游戏"?
前端·人工智能·ios
小岛前端1 小时前
Node.js 宣布重大调整,运行十年的规则要改了!
前端·node.js
OpenTiny社区1 小时前
OpenTiny NEXT-SDK 重磅发布:四步把你的前端应用变成智能应用
前端·javascript·ai编程
梦想CAD控件1 小时前
在线CAD开发包结构与功能说明
前端·javascript·vue.js