vue实现表格滚动
Vue 实现表格滚动的方法
使用 CSS 固定表头并滚动内容
通过 CSS 设置表格容器的固定高度和 overflow-y: auto,实现内容滚动而表头固定。
<template>
<div class="table-container">
<table>
<thead>
<tr>
<th v-for="col in columns" :key="col">{{ col }}</th>
</tr>
</thead>
<tbody>
<tr v-for="row in data" :key="row.id">
<td v-for="col in columns" :key="col">{{ row[col] }}</td>
</tr>
</tbody>
</table>
</div>
</template>
<style scoped>
.table-container {
height: 300px;
overflow-y: auto;
}
thead {
position: sticky;
top: 0;
background: white;
}
</style>
使用第三方库(如 Element UI)
Element UI 的 el-table 组件内置滚动功能,通过 max-height 属性控制。

<template>
<el-table :data="data" max-height="300">
<el-table-column v-for="col in columns" :key="col" :prop="col" :label="col" />
</el-table>
</template>
虚拟滚动优化性能
对于大数据量,使用虚拟滚动库(如 vue-virtual-scroller)减少 DOM 渲染压力。

<template>
<RecycleScroller
class="scroller"
:items="data"
:item-size="50"
key-field="id"
>
<template v-slot="{ item }">
<div class="row">
<span v-for="col in columns" :key="col">{{ item[col] }}</span>
</div>
</template>
</RecycleScroller>
</template>
横向滚动支持
通过 CSS 的 overflow-x: auto 实现横向滚动。
<div class="horizontal-scroll">
<table>
<!-- 宽表格内容 -->
</table>
</div>
<style>
.horizontal-scroll {
overflow-x: auto;
white-space: nowrap;
}
</style>
动态加载数据滚动
监听滚动事件,滚动到底部时加载更多数据。
methods: {
handleScroll() {
const container = this.$refs.container;
if (container.scrollTop + container.clientHeight >= container.scrollHeight) {
this.loadMoreData();
}
}
}
注意事项
- 固定表头时需确保
thead背景色与页面一致,避免重叠视觉问题。 - 虚拟滚动需计算每行高度,动态数据需重置滚动位置。
- 横向滚动时内容需设置
white-space: nowrap防止换行。






