vue表格置顶实现
实现 Vue 表格置顶的方法
使用 CSS 固定表头
通过 CSS 的 position: sticky 属性可以轻松实现表格表头的置顶效果。这种方法不需要额外的 JavaScript 代码,纯 CSS 实现。
<template>
<div class="table-container">
<table>
<thead>
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
</thead>
<tbody>
<tr v-for="item in items" :key="item.id">
<td>{{ item.name }}</td>
<td>{{ item.value }}</td>
</tr>
</tbody>
</table>
</div>
</template>
<style scoped>
.table-container {
height: 300px;
overflow-y: auto;
}
thead th {
position: sticky;
top: 0;
background-color: white;
z-index: 10;
}
</style>
使用第三方表格组件
许多 Vue 表格组件库如 Element UI、Ant Design Vue 等都内置了表头固定功能。

以 Element UI 为例:

<template>
<el-table
:data="tableData"
height="250"
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>
自定义滚动监听实现
当需要更复杂的控制时,可以通过监听滚动事件来实现表头固定。
<template>
<div class="scroll-container" @scroll="handleScroll">
<table>
<thead :class="{ 'fixed-header': isFixed }">
<tr>
<th>Header</th>
</tr>
</thead>
<tbody>
<!-- 表格内容 -->
</tbody>
</table>
</div>
</template>
<script>
export default {
data() {
return {
isFixed: false
}
},
methods: {
handleScroll(e) {
this.isFixed = e.target.scrollTop > 0
}
}
}
</script>
<style>
.fixed-header {
position: fixed;
top: 0;
width: 100%;
background: white;
}
</style>
使用 Intersection Observer API
现代浏览器支持的 Intersection Observer API 可以实现更高效的滚动检测。
export default {
mounted() {
const observer = new IntersectionObserver((entries) => {
this.isFixed = !entries[0].isIntersecting
}, { threshold: [1] })
observer.observe(this.$refs.triggerElement)
}
}






