vue实现固定表格
Vue 实现固定表格的方法
使用 CSS 固定表头
通过 CSS 的 position: sticky 属性可以轻松实现表头固定。需要为表头元素添加 sticky 类,并设置 top: 0 以固定在顶部。
<template>
<div class="table-container">
<table>
<thead>
<tr class="sticky-header">
<th>Header 1</th>
<th>Header 2</th>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in items" :key="index">
<td>{{ item.name }}</td>
<td>{{ item.value }}</td>
</tr>
</tbody>
</table>
</div>
</template>
<style scoped>
.table-container {
height: 300px;
overflow-y: auto;
}
.sticky-header {
position: sticky;
top: 0;
background-color: white;
z-index: 10;
}
</style>
使用第三方库
如果项目复杂度较高,可以考虑使用专门处理表格的第三方库,如 vue-good-table 或 element-ui 的表格组件。
<template>
<el-table :data="items" height="300px">
<el-table-column prop="name" label="Header 1"></el-table-column>
<el-table-column prop="value" label="Header 2"></el-table-column>
</el-table>
</template>
<script>
import { ElTable, ElTableColumn } from 'element-ui';
export default {
components: { ElTable, ElTableColumn },
data() {
return {
items: [
{ name: 'Item 1', value: 'Value 1' },
{ name: 'Item 2', value: 'Value 2' }
]
};
}
};
</script>
动态计算高度
对于需要动态计算表格高度的情况,可以通过监听窗口大小变化或父容器高度变化来调整表格高度。
<template>
<div ref="tableContainer" class="table-container">
<table>
<thead class="sticky-header">
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in items" :key="index">
<td>{{ item.name }}</td>
<td>{{ item.value }}</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
export default {
data() {
return {
items: [...],
containerHeight: 0
};
},
mounted() {
this.updateHeight();
window.addEventListener('resize', this.updateHeight);
},
beforeDestroy() {
window.removeEventListener('resize', this.updateHeight);
},
methods: {
updateHeight() {
this.containerHeight = this.$refs.tableContainer.clientHeight;
}
}
};
</script>
固定列的实现
如果需要固定左侧或右侧列,可以通过额外的 CSS 和结构设计实现。
<template>
<div class="fixed-column-table">
<div class="fixed-column">
<table>
<thead>
<tr class="sticky-header">
<th>Fixed Header</th>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in items" :key="index">
<td>{{ item.name }}</td>
</tr>
</tbody>
</table>
</div>
<div class="scrollable-column">
<table>
<thead>
<tr class="sticky-header">
<th>Scrollable Header</th>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in items" :key="index">
<td>{{ item.value }}</td>
</tr>
</tbody>
</table>
</div>
</div>
</template>
<style scoped>
.fixed-column-table {
display: flex;
overflow-x: auto;
}
.fixed-column {
position: sticky;
left: 0;
background-color: white;
z-index: 20;
}
.scrollable-column {
flex: 1;
}
</style>
以上方法可以根据实际需求选择或组合使用,实现灵活的表格固定效果。







