uniapp uni-table 表头固定
时间: 2025-01-20 07:04:44 浏览: 102
### 实现 uni-app 中 `uni-table` 组件表头固定的效果
为了实现在 `uni-app` 的 `uni-table` 组件中保持表头固定的功能,可以采用分层布局的方式。具体来说,在页面上创建两个独立的部分:一部分用于显示固定的表头,另一部分则用来展示滚动的数据列表。
#### HTML 结构设计
通过定义两组表格标签分别对应头部和主体内容,并利用 CSS 设置样式使得顶部区域始终可见而下方的内容支持上下滑动查看更多数据项[^1]:
```html
<template>
<view class="table-container">
<!-- 表格头部 -->
<view class="fixed-header">
<uni-table>
<tr>
<th v-for="(header, index) in headers" :key="index">{{ header }}</th>
</tr>
</uni-table>
</view>
<!-- 数据区 -->
<scroll-view scroll-y style="height: calc(100vh - 50px);">
<uni-table>
<tbody>
<tr v-for="(row, rowIndex) in dataRows" :key="rowIndex">
<td v-for="(cell, cellIndex) in row" :key="cellIndex">{{ cell }}</td>
</tr>
</tbody>
</uni-table>
</scroll-view>
</view>
</template>
```
#### 样式调整
对于上述模板中的 `.fixed-header` 类名应用特定的定位属性以确保其不会随着页面其他元素一起移动;同时设置适当的高度值防止遮挡实际数据显示范围:
```css
<style scoped>
.table-container {
position: relative;
}
.fixed-header {
position: sticky;
top: 0; /* 粘性定位 */
background-color: white;
z-index: 999;
}
</style>
```
#### JavaScript 配置
最后,在 Vue 组件内部初始化所需变量并填充模拟测试用的数据集以便于观察效果:
```javascript
<script>
export default {
name: 'FixedTableHeader',
data() {
return {
headers: ['列1', '列2', '列3'],
dataRows: Array.from({ length: 10 }, () => [
Math.floor(Math.random() * 10),
Math.floor(Math.random() * 10),
Math.floor(Math.random() * 10)
])
}
},
};
</script>
```
阅读全文
相关推荐


















