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

<template>
<el-table :data="tableData" height="400">
<el-table-column prop="date" label="日期"></el-table-column>
<el-table-column prop="name" label="姓名"></el-table-column>
</el-table>
</template>
实现横向滚动
通过设置 overflow-x: auto 和固定列宽实现横向滚动。

<div class="horizontal-scroll">
<table>
<tr>
<td v-for="item in items" :key="item.id" class="fixed-width">{{ item.name }}</td>
</tr>
</table>
</div>
<style>
.horizontal-scroll {
overflow-x: auto;
}
.fixed-width {
width: 200px;
}
</style>
虚拟滚动优化大数据量
使用 vue-virtual-scroller 等库实现虚拟滚动,仅渲染可见区域元素。
<template>
<RecycleScroller
class="scroller"
:items="list"
:item-size="50"
key-field="id"
>
<template v-slot="{ item }">
<div class="item">{{ item.name }}</div>
</template>
</RecycleScroller>
</template>
监听滚动事件实现特殊效果
通过 @scroll 事件监听实现滚动加载更多等交互。
<div class="scroll-wrapper" @scroll="handleScroll">
<!-- 表格内容 -->
</div>
<script>
export default {
methods: {
handleScroll(e) {
const bottom = e.target.scrollHeight - e.target.scrollTop === e.target.clientHeight
if (bottom) this.loadMore()
}
}
}
</script>
选择合适的方法取决于具体需求:简单滚动可使用 CSS 方案;需要丰富功能建议使用组件库;大数据量场景推荐虚拟滚动。






