效果如图:
红框内是我们的表头,正常表格都是表头在上,我们这边实现了表头在左,动态数据在右
代码如下:
1,声明表格,使用框架自带的a-table,核心点在data和columns上
我们先来看一下正常使用的a-table:
<a-table
bordered // 展示外边框和列边框
:columns="columns" // 自己定义的表格列的配置数组
:data-source="publicData" // 后端返回的动态数据
:scroll="{ x: 1500, y: '50vh' }" // 指定滚动区域的宽和高
:pagination="false" // 分页器
:rowKey="(record) => record.id" // 表格行 key 的取值
>
</a-table>
再来看一下表头在左的a-table
<a-table
bordered
:columns="areaHeader"
data-source="getValues()" // 数据数组,这里的数据数组是个方法,下面会讲
:pagination="false"
:rowKey="(record,index) => index"
:showHeader="false" // 是否显示表头
>
</a-table>
会发现有两处改动,我们的data-source变成了一个方法,新增了一个shouHeader的API
2,设置表头columns:
//label是表头,props是对应的数据。这里换成你们自己的数据即可
const columns = [
{
label: "项目",
props: "scheme_name",
},
{ label: "单位最低基数", props: "unit_min"},
{
label: "单位最高基数",
props: "unit_highest",
},
{
label: "个人最低基数",
props: "staff_min",
},
{
label: "个人最高基数",
props: "staff_highest",
},
{
label: "单位收款方式",
props: "unit_payment",
},
{
label: "单位参保规则",
props: "unit_insured_rule",
},
{
label: "单位比例",
props: "unit_proportion",
},
{
label: "单位最低金额",
props: "unit_minPrice",
},
{
label: "单位最高金额",
props: "unit_maxPrice",
},
{
label: "单位补缴",
props: "unit_supplementary",
},
{
label: "个人收款方式",
props: "staff_payment",
},
{
label: "个人参保规则",
props: "staff_insured_rule",
},
{
label: "个人比例",
props: "staff_proportion",
},
{
label: "个人最低金额",
props: "staff_minPrice",
},
{
label: "个人最高金额",
props: "staff_maxPrice",
},
{
label: "个人补缴",
props: "staff_supplementary",
},
{
label: "最低合计",
props: "minPrice",
},
{
label: "最高合计",
props: "maxPrice",
},
{
label: "扣款日期",
props: "deduction_date",
}
];
3,绑定数据-js部分
记得在data里声明一个areaHeader:[],// 转换表头
在methods中:
// 转换表头
getHeaders () {
let data = this.columns.reduce((pre, cur, index) => pre.concat({ 'dataIndex': `value${index}` }), [{ 'dataIndex': 'title' }])
console.log('headers===>', data)
this.areaHeader = data
},
// 转换绑定数据
getValues () {
let data = this.columns.map(item => {
return this.formPro.settlement.reduce((pre, cur, index) => Object.assign(pre, { ['value' + index]: cur[item.props] }), { 'title': item.label })
})
console.log('value===>', data)
return data
},
最后在created里面执行一下this.getHeaders();就可以了
这里实现的思路是注册空数组,循环遍历成为一个新的数组,从打印的数据里可以看到,会生成一个新数组是我们转换过的,这就是为什么我们在上面data-source从后端返回的动态数据换成了我们getValues的方法。到这一步就可以实现表头纵排列了。如果还有什么疑问可以评论区留言讨论
antd组件a-table地址:Ant Design Vue