需求:固定表头数据,在网上找了半天,啥都有,就是一直实现不了,最后更改代码实现
1.效果
2.主要代码讲解+完整代码
表格的父级一定要设置高度,不然会错位,我看网上说设置position:fixed,我觉得没必要,给父级设置position: relative;,表头设置position: absolute就可以定位到想要的位置了,但是这样会导致脱离标准文档流,所以还要在表格内容设置个margin-top:44px.44px是表头的高度,复制如下代码即可实现需求~
<template>
<view class="uni-container">
<uni-table ref="table" border stripe emptyText="暂无更多数据">
<view class="tableHead">
<uni-tr>
<uni-th align="center">
<view style="width:50px;">姓名</view>
</uni-th>
<uni-th align="center">
<view style="width:50px;">部门</view>
</uni-th>
<uni-th align="center">
<view style="width:50px;">职位</view>
</uni-th>
<uni-th align="center">
<view style="width:50px;">角色</view>
</uni-th>
</uni-tr>
</view>
<view class="tableBody" >
<uni-tr v-for="(item, index) in tableData" :key="index">
<uni-td>
<view style="width:50px;">{{item.realname}}</view>
</uni-td>
<uni-td>
<view style="width:50px;">{{item.name}}</view>
</uni-td>
<uni-td>
<view style="width:50px;">{{item.post || ''}}</view>
</uni-td>
<uni-td>
<view style="width:50px;">{{item.roleName}}</view>
</uni-td>
</uni-tr>
</view>
</uni-table>
</view>
</template>
<script>
export default {
data() {
return {
loading: false,
tableData: [{
name: '382'
}, {
name: '382'
}],
}
},
mounted() {
const result = [];
for (let i = 0; i < 100; i++) {
result.push({
date: new Date().toISOString(),
realname: '张三',
name: '研发',
post:'11'
})
}
this.tableData = result;
}
}
</script>
<style lang="scss">
.uni-container {
height: 500rpx;
margin-top: 50rpx;
position: relative;
}
/* //表头固定样式 */
::v-deep .tableHead {
font-weight: bold;
color: #333333;
background: #F4F6FF;
z-index: 20;
position: absolute;
top: 0rpx;
}
::v-deep .tableBody {
height: 500px;
overflow: scroll;
margin-top: 44px;
background-color: #fff;
}
</style>
文章到处结束,希望对你有所帮助~