文章目录
- table.wxml
- table.wxss
- 注意
- table.js
- 注意
- 结果
- 数据结构
最近菜鸟做微信小程序的一个查询功能,需要展示excel里面的数据,但是菜鸟找了一圈,也没发现什么组件库有table,毕竟手机端好像确实不太适合做table!
菜鸟只能自己封装一个table了,当然菜鸟就是简单的封装,只是为自己留一个记录,免得后面要实现类似的东西去翻代码,对大佬们肯定是没啥帮助,但是对小白可能有点启发!
table.wxml
<view class="table-container"><scroll-view scroll-x="true" scroll-y="true" class="table-body"style="max-height: {{height}}"enhanced="true"show-scrollbar="false"><view class="table"><!-- 固定表头 --><view class="table-header"><view class="tr"><block wx:for="{{columns}}" wx:key="index"><viewclass="th"style="min-width: {{item.width || '300rpx'}};width: {{item.width || '300rpx'}};">{{ item.name }}</view></block></view></view><!-- 表格内容 --><view class="table-rows"><block wx:for="{{listData}}" wx:key="item"><view class="tr borderbtm"><block wx:for="{{columns}}" wx:for-item="cell" wx:key="cell"> <viewclass="td"style="min-width: {{cell.width || '300rpx'}};width: {{cell.width || '300rpx'}};">{{item[cell.key]}}</view></block></view></block></view></view></scroll-view>
</view>
table.wxss
.table-container {width: 100%;
}.table-body {width: 100%;
}.table {width: fit-content;min-width: 100%;
}.table-header {position: sticky; //position: sticky 是相对于最近的可滚动祖先元素,也就是 scroll-view.table-body 元素top: 0;z-index: 1;background: #fff;
}.tr {display: flex;white-space: nowrap;
}.th,
.td {display: inline-flex;align-items: center;box-sizing: border-box;padding: 20rpx;word-break: break-all;word-wrap: break-word;white-space: normal;user-select: text; /* 添加这行使文本可选择 */
}.td {-webkit-user-select: text; /* 兼容性处理 */cursor: text; /* 显示文本选择光标 */
}.th {font-weight: bold;background-color: #f8f8f8;
}.borderbtm {border-bottom: 1px solid #eee;
}
注意
table.js
Component({properties: {listData: {type: Array,value: "",},columns: {type: Array,value: "",},height: {type: String,value: "",},},lifetimes: {attached() {const windowInfo = wx.getWindowInfo();const menuButtonInfo = wx.getMenuButtonBoundingClientRect();const headerHeight = menuButtonInfo.bottom + 40;const tableHeight = `${(windowInfo.windowHeight - headerHeight) / 2}px`;this.setData({height: tableHeight,});},},
});
注意
菜鸟这里是正好两个表要一上一下对半占屏幕,要是不是,可以不要计算这里的部分,直接靠传参设置!
结果
有图有真相
数据结构
表头
b2_header_title: [{ name: "客户批次号", key: "customerBatchNum" },{ name: "项目批次号", key: "projectBatchNum" },{ name: "执行合同编号", key: "executionContractNum", width: "500rpx" },{ name: "执行合同名称", key: "executionContractName", width: "1000rpx" },……
]
数据
[{"id": "2441568","customerBatchNum": "SP2410303188","projectBatchNum": "BC2024110238","executionContractNum": "BN2401105NJ01S02N2","executionContractName": "xxxxx","uploadTime": "2025-04-01 14:31:18",……},{"id": "2441570","customerBatchNum": "SP2410303178","projectBatchNum": "BC2024110239","executionContractNum": "BN2401105NJ01S02N2","executionContractName": "xxxxxxx","uploadTime": "2025-04-01 14:32:18",……}
]