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数据,只适用固定行高度的场景

相关推荐
ayqy贾杰2 分钟前
Cursor SDK发布!开发者可直接搬走其内核
前端·vue.js·面试
changshuaihua0014 分钟前
扣子开发指南
javascript·人工智能
椰猫子10 分钟前
SpringMVC(SpringMVC简介、请求与响应(请求映射路径、请求参数、日期类型参数传递、响应json数据))
java·前端·数据库
love530love14 分钟前
如何在 Google Chrome 中强制开启 Gemini AI 侧边栏(完整图文教程)
前端·人工智能·chrome·windows
光影少年15 分钟前
对typescript开发框架的理解?
前端·javascript·typescript
跨境数据猎手19 分钟前
反向海淘代购系统:1688 / 淘宝自动代采 + API 同步(附可用源码)
前端
lUie INGA24 分钟前
Go-Gin Web 框架完整教程
前端·golang·gin
a11177626 分钟前
“像风之翼“无人机巡检平台仪表盘
前端·javascript·开源·html·无人机
李白的天不白30 分钟前
vue 数据格式问题
前端·vue.js·windows
小白蒋博客30 分钟前
【ai开发段永平投资理财的知识图谱网站】第一天:搭 Vite + Vue 项目,跑通 Hello World
vue.js·人工智能·trae