一个基于 Vue 3 的高性能虚拟滚动组件,适用于渲染大量数据的场景。通过仅渲染可视区域内的元素并结合 rem 动态计算高度,实现流畅的滚动体验。
- ✅ 虚拟滚动:只渲染当前可视区域内的列表项,提升性能。
- 💡 动态高度支持:使用 rem 和传入的根字号进行高度计算,适配响应式布局。
- 🧩 插槽支持:可自定义列表项内容。
- 🎛️ 滚动控制:提供方法支持程序化滚动到指定位置(支持平滑滚动)。
- 🌐 兼容 Vue 3 <script setup> 语法
npm install long-list-scroll-rem
Or via yarn:
yarn add long-list-scroll-rem
// main.js or main.ts
import { createApp } from 'vue'
import App from './App.vue'
import LongListScrollRem from 'long-list-scroll-rem'
const app = createApp(App)
app.use(LongListScrollRem)
app.mount('#app')
<template>
<div class="list-container">
<LongListScrollRem :list-data="data" :height="2" :root-font-size="16" key="id" ref="listRef">
<template #default="{ item }">
<div>{{ item.label }}</div>
</template>
</LongListScrollRem>
</div>
</template>
<script setup>
import { ref } from 'vue'
import { LongListScrollRem } from 'long-list-scroll-rem'
const data = ref([
{ id: 0, label: 'Item 0' },
{ id: 1, label: 'Item 1' }
// ...更多数据
])
const listRef = ref(null)
function scrollToIndex() {
listRef.value.handleSrollTopSize({ index: 20 })
}
</script>
<style scoped>
.list-container {
height: 500px;
overflow: hidden;
}
</style>
Property | Type | Default | Description |
---|---|---|---|
listData |
Array | [] |
列表数据数组,每个元素应包含唯一标识符字段 |
height |
Number | 100 |
每个列表项的基础高度;rootFontSize=0 时,默认使用 html 根字号去计算每行高度;rootFontSize=1 时,默认每行高度为 height 值 |
rootFontSize |
Number | 0 |
页面根字号(用于 rem 计算);当 为 0 时,默认使用 html 根字号去计算每行 height;当为 1 时,默认每行高度为出入的 height 值 |
key |
String | id |
数据中作为唯一标识的字段名 |
handleSrollTopSize()
//默认传入参数
{
top: 0, // 滚动的目标位置
behavior: 'smooth', // 滚动行为,如 'auto' 或 'smooth',可不配置默认为'smooth
index: null // 如果提供,则根据 index 计算 scrollTop, (优先级高于 top)
}
listRef.value.handleSrollTopSize() //默认滚动到顶部,smooth滚动
listRef.value.handleSrollTopSize({ index: 10 }) // 滚动到第 10 项
listRef.value..handleSrollTopSize({ top: 500 }) // 滚动到 500px 位置
MIT License