当前位置: 首页 > news >正文

vue长列表,虚拟滚动

1.新建子组件,将数据传递过去(几万条数据的数组,一次性展示多少条,每条数据的行高).

<template><div class="vitualScroll"><sub-scroll :dataList="dataList" :rowCount="20" :rowHeight="20"></sub-scroll></div>
</template><script>
import subScroll from "./components/subScroll.vue"
export default{name: 'virtualScroll',data(){return {//冻结数组,初步优化dataList: Object.freeze(new Array(20000).fill(null).map((item, index) => ({ n: index+1 })))}},components:{subScroll}
}
</script>
<style scoped lang="less">
.vitualScroll{width: 100%;height: 100%;
}
</style>

2.子组件subScroll.vue

div.scrollBar用来使父盒子出现滚动条,div.scrollBar的高度就是数据总条数*单条数据的高度。

div.list才是v-for数据的盒子,采用绝对定位,在父元素滑动事件中更新数据,并且将div.list的位置拉回来(div.list采用绝对定位,滑动滚动会往上跑)

<template><div class="scrollView" ref="scrollView" :style="{'--rowHeight': $props.rowHeight + 'px'}" @scroll="onScroll()"><div class="scrollBar" :style="{'--scrollBarHeight': $props.dataList.length * $props.rowHeight + 'px'}"></div><div class="list" ref="list"><div class="item" v-for="(item, index) in copyDataList" :key="index">{{ item.n }}</div></div></div>
</template><script>
export default{name: 'subScroll',data(){return {start: 0}},computed:{copyDataList(){return this.$props.dataList.slice(this.start, this.$props.rowCount + this.start)}},props:{dataList: {type: Array,default(){return [{}]}},rowCount: {type: Number,default: 0},rowHeight: {type: Number,default: 0}},mounted(){},methods: {onScroll(){//全局节流函数this.$throttle(this.updataData, 50)},updataData(){let offsetTop = this.$refs.scrollView.scrollToplet offsetNum = Math.round(offsetTop / this.$props.rowHeight)this.start = offsetNumthis.$refs.list.style.transform = `translateY(${offsetTop}px)`console.log('滑动的距离', offsetTop)}}
}
</script><style lang="less" scoped>
.scrollView{width: 200px;height: 400px;overflow: auto;position: relative;.item{height: var(--rowHeight);}.scrollBar{height: var(--scrollBarHeight);}.list{position: absolute;top: 0;left: 0;right: 0;bottom: 0;}
}
</style>

http://www.lryc.cn/news/389899.html

相关文章:

  • 【实战场景】记一次UAT jvm故障排查经历
  • 线性代数--行列式1
  • tensorflow神经网络
  • Python基础001
  • 【udp报文】udp报文未自动分片,报文过长被拦截问题定位
  • 某网页gpt的JS逆向
  • 【python脚本】批量检测sql延时注入
  • 在C++中如何理解const关键字的不同用法(如const变量、const成员函数、const对象等)
  • JavaSEJava8 时间日期API + 使用心得
  • 【亲测解决】Python时间问题
  • Linux屏幕驱动开发调试笔记
  • Nginx Http缓存的必要性!启发式缓存有什么弊端?
  • 【RT摩拳擦掌】RT云端测试之百度天工物接入构建(设备型)
  • Mysql和ES使用汇总
  • Android中使用performClick触发点击事件
  • 重生之我要学后端01--后端语言选择和对应框架选择
  • C语言 | Leetcode C语言题解之第206题反转链表
  • Flink Window DEMO 学习
  • library source does not match the bytecode for class SpringApplication
  • Linux基础指令介绍与详解——原理学习
  • 【代码随想录算法训练Day52】LeetCode 647. 回文子串、LeetCode 516.最长回文子串
  • VUE项目安全漏洞扫描和修复
  • Nginx主配置文件---Nginx.conf
  • IOS Swift 从入门到精通:写入 Firestore数据库
  • 维克日记 v0.4.2:开发者友好的数字化笔记工具
  • 语音房平台交友,语聊APP系统开发线上语音交友平台成熟案例源码出售
  • VMamba: Visual State Space Model论文笔记
  • 探索哈希函数:数据完整性的守护者
  • 解析Kotlin中的Unit【笔记摘要】
  • 仿论坛项目--初识Spring Boot