vue实现table表格滚动
实现固定表头滚动
使用CSS固定表头,表格内容区域滚动:
<template>
<div class="scroll-table-container">
<table>
<thead>
<tr>
<th v-for="col in columns" :key="col.key">{{ col.title }}</th>
</tr>
</thead>
<tbody>
<tr v-for="(row, index) in data" :key="index">
<td v-for="col in columns" :key="col.key">{{ row[col.key] }}</td>
</tr>
</tbody>
</table>
</div>
</template>
<style scoped>
.scroll-table-container {
height: 400px;
overflow-y: auto;
}
table {
width: 100%;
border-collapse: collapse;
}
thead {
position: sticky;
top: 0;
background: white;
z-index: 10;
}
th, td {
padding: 8px 16px;
border: 1px solid #ddd;
}
</style>
使用第三方组件库
Element UI的el-table组件自带滚动功能:
<template>
<el-table
:data="tableData"
height="400"
style="width: 100%">
<el-table-column
prop="date"
label="日期"
width="180">
</el-table-column>
<el-table-column
prop="name"
label="姓名"
width="180">
</el-table-column>
</el-table>
</template>
横向滚动实现
为表格容器添加横向滚动条:
.table-container {
width: 100%;
overflow-x: auto;
white-space: nowrap;
}
虚拟滚动优化性能
对于大数据量表格,使用vue-virtual-scroller:
<template>
<RecycleScroller
class="scroller"
:items="data"
:item-size="50"
key-field="id">
<template v-slot="{ item }">
<div class="row">
<div v-for="col in columns" :key="col.key">
{{ item[col.key] }}
</div>
</div>
</template>
</RecycleScroller>
</template>
<style>
.scroller {
height: 400px;
}
.row {
display: flex;
border-bottom: 1px solid #eee;
height: 50px;
align-items: center;
}
.row > div {
flex: 1;
padding: 0 10px;
}
</style>
自定义滚动事件监听
通过监听滚动事件实现特殊效果:
mounted() {
const tableBody = document.querySelector('.table-container tbody')
tableBody.addEventListener('scroll', this.handleScroll)
},
methods: {
handleScroll(event) {
const { scrollTop, clientHeight, scrollHeight } = event.target
if (scrollHeight - scrollTop === clientHeight) {
// 滚动到底部加载更多数据
}
}
}
响应式表格高度
动态计算表格容器高度:
computed: {
tableHeight() {
return window.innerHeight - 200 // 减去页眉页脚等固定高度
}
},
mounted() {
window.addEventListener('resize', this.handleResize)
},
beforeDestroy() {
window.removeEventListener('resize', this.handleResize)
}






