vue实现表格滚动
Vue 实现表格滚动的方法
使用 CSS 固定表头并滚动内容
通过 CSS 设置表格容器的固定高度和 overflow-y: auto,实现内容区域的滚动。表头部分使用 position: sticky 固定。
<template>
<div class="table-container">
<table>
<thead>
<tr>
<th v-for="header in headers" :key="header">{{ header }}</th>
</tr>
</thead>
<tbody>
<tr v-for="row in data" :key="row.id">
<td v-for="header in headers" :key="header">{{ row[header] }}</td>
</tr>
</tbody>
</table>
</div>
</template>
<style scoped>
.table-container {
height: 300px;
overflow-y: auto;
}
thead th {
position: sticky;
top: 0;
background: white;
}
</style>
使用第三方库实现高级滚动
对于复杂需求(如虚拟滚动、横向滚动),可使用 vue-virtual-scroller 或 element-ui 的表格组件。

安装 vue-virtual-scroller:
npm install vue-virtual-scroller
示例代码:

<template>
<RecycleScroller
class="scroller"
:items="data"
:item-size="50"
key-field="id"
>
<template v-slot="{ item }">
<div class="row">
<span v-for="header in headers" :key="header">{{ item[header] }}</span>
</div>
</template>
</RecycleScroller>
</template>
<script>
import { RecycleScroller } from 'vue-virtual-scroller';
export default {
components: { RecycleScroller },
data() {
return {
headers: ['name', 'age', 'gender'],
data: [...]
};
}
};
</script>
<style>
.scroller {
height: 300px;
}
.row {
display: flex;
padding: 10px;
border-bottom: 1px solid #eee;
}
.row span {
flex: 1;
}
</style>
横向滚动实现
通过 CSS 设置 overflow-x: auto 和固定列宽实现横向滚动。
<template>
<div class="horizontal-scroll">
<table>
<thead>...</thead>
<tbody>...</tbody>
</table>
</div>
</template>
<style>
.horizontal-scroll {
overflow-x: auto;
white-space: nowrap;
}
.horizontal-scroll table {
width: auto;
}
.horizontal-scroll th,
.horizontal-scroll td {
min-width: 120px;
}
</style>
动态加载数据滚动
监听滚动事件,滚动到底部时加载更多数据。
methods: {
handleScroll(e) {
const { scrollTop, clientHeight, scrollHeight } = e.target;
if (scrollHeight - (scrollTop + clientHeight) < 50) {
this.loadMoreData();
}
}
}






