vue 实现表格固定列
Vue 实现表格固定列的方法
使用 CSS 固定列
通过 CSS 的 position: sticky 属性可以实现列的固定效果。适用于简单的表格布局,无需额外库支持。
<template>
<div class="table-container">
<table>
<thead>
<tr>
<th class="fixed-column">固定列</th>
<th>列1</th>
<th>列2</th>
</tr>
</thead>
<tbody>
<tr v-for="item in data" :key="item.id">
<td class="fixed-column">{{ item.fixed }}</td>
<td>{{ item.col1 }}</td>
<td>{{ item.col2 }}</td>
</tr>
</tbody>
</table>
</div>
</template>
<style scoped>
.table-container {
overflow-x: auto;
max-width: 100%;
}
.fixed-column {
position: sticky;
left: 0;
background-color: white;
z-index: 1;
}
</style>
使用第三方库(如 Element UI)
Element UI 的 el-table 组件内置固定列功能,通过 fixed 属性即可实现。
<template>
<el-table :data="data" style="width: 100%">
<el-table-column prop="fixed" label="固定列" fixed width="150"></el-table-column>
<el-table-column prop="col1" label="列1" width="200"></el-table-column>
<el-table-column prop="col2" label="列2" width="200"></el-table-column>
</el-table>
</template>
自定义滚动监听
对于复杂场景,可通过监听滚动事件动态控制列的样式。
<template>
<div class="scroll-container" @scroll="handleScroll">
<table>
<thead>
<tr>
<th :class="{ 'fixed-column': isFixed }">固定列</th>
<th>列1</th>
</tr>
</thead>
<tbody>
<tr v-for="item in data" :key="item.id">
<td :class="{ 'fixed-column': isFixed }">{{ item.fixed }}</td>
<td>{{ item.col1 }}</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
export default {
data() {
return {
isFixed: false
};
},
methods: {
handleScroll(e) {
this.isFixed = e.target.scrollLeft > 0;
}
}
};
</script>
性能优化建议
- 固定列数量不宜过多,避免渲染性能问题。
- 大数据量时建议使用虚拟滚动(如
vue-virtual-scroller)。 - 第三方库的固定列功能通常已优化,优先考虑使用。
以上方法可根据项目需求选择,CSS 方案轻量但功能有限,第三方库功能全面但体积较大。







