vue实现table表格滚动
Vue 实现表格滚动的方法
使用 CSS 固定表头并滚动内容
通过 CSS 设置表格容器的高度和溢出属性,实现表头固定、内容滚动的效果。
<template>
<div class="table-container">
<table>
<thead>
<tr>
<th v-for="col in columns" :key="col.key">{{ col.title }}</th>
</tr>
</thead>
<tbody>
<tr v-for="row in data" :key="row.id">
<td v-for="col in columns" :key="col.key">{{ row[col.key] }}</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 或 Ant Design Vue 等库提供了现成的滚动表格组件。

<template>
<el-table :data="tableData" height="250">
<el-table-column prop="date" label="日期"></el-table-column>
<el-table-column prop="name" label="姓名"></el-table-column>
</el-table>
</template>
虚拟滚动优化性能
对于大数据量表格,使用虚拟滚动技术只渲染可见区域的行。

<template>
<virtual-list :size="50" :remain="10" :data="bigData">
<table>
<tr v-for="item in virtualData" :key="item.id">
<td>{{ item.name }}</td>
</tr>
</table>
</virtual-list>
</template>
横向滚动实现
当列数过多时,可以添加水平滚动条。
.table-container {
overflow-x: auto;
white-space: nowrap;
}
动态计算高度
根据窗口大小动态调整表格高度。
mounted() {
this.calcHeight();
window.addEventListener('resize', this.calcHeight);
},
methods: {
calcHeight() {
this.tableHeight = window.innerHeight - 200;
}
}
以上方法可以根据实际需求选择使用,CSS 方案最简单,虚拟滚动适合大数据量,组件库方案最便捷。






