Table 表格
何时使用
table组件实现动态列+表头下拉选择功能
效果图
table组件实现动态列
先看数据结构:
要求:根据第一条数据中的noBelongCols
字段,创建动态列。
changeColumns(){
let noBelongCols =
this.tableList && this.tableList[0] && this.tableList[0].noBelongCols;
console.log('noBelongCols', noBelongCols, this.columns);
this.noBelongCols = noBelongCols;
this.noBelongTypes = [];
noBelongCols &&
noBelongCols.forEach((be, index) => {
this.columns.push({
slots: { title: '无主列' + index },
type: 'string',
dataIndex: '无主列' + index,
width: 110,
scopedSlots: { customRender: '无主列' + index },
});
this.noBelongTypes.push(undefined);
this.tableList.forEach((table) => {
table['无主列' + index] = table['noBelongCols'][index];
});
});
this.columns.push({
title: '操作',
scopedSlots: { customRender: 'action' },
align: 'center',
width: 60,
fixed: 'right',
});
}
table组件表头自定义——slots: { title: ‘无主列’ + index }
由于动态列的长度不固定,因此需要用v-for
进行遍历,遍历出多列。
v-for="(be, bIndex) in noBelongCols" :key="bIndex" :slot="'无主列' + bIndex"
<a-table
:rowKey="(r, i) => i.toString()"
:columns="columns"
:dataSource="tableList"
>
<div
v-for="(be, bIndex) in noBelongCols"
:key="bIndex"
:slot="'无主列' + bIndex"
>
<a-select v-model="noBelongTypes[bIndex]" style="width: 100px">
<a-select-option
v-for="item in titleOptions"
:key="item"
:value="item"
>{{ item }}</a-select-option
>
</a-select>
</div>
</a-table>
表格头部自定义的处理方法:
1.使用slots:{title:'无主列'}
遍历动态列的时候,设置自定义表头和自定义表格内容
this.columns.push({
slots: { title: '无主列' + index },
type: 'string',
dataIndex: '无主列' + index,
width: 110,
scopedSlots: { customRender: '无主列' + index },
});
2.在table
组件中使用slot='xxxx'
的方式来处理
最终代码如下:
<div
v-for="(be, bIndex) in noBelongCols"
:key="bIndex"
:slot="'无主列' + bIndex"
>
<a-select v-model="noBelongTypes[bIndex]" style="width: 100px">
<a-select-option
v-for="item in titleOptions"
:key="item"
:value="item"
>{{ item }}</a-select-option
>
</a-select>
</div>
完成!!!多多积累,多多收获!!!
下面内容与文章相关不大,只是为了凑字数,可忽略!!!
.ant-table{
:global {
width: 98%;
margin-left: 1%;
.ant-table-thead > tr > th, .ant-table-tbody > tr > td {
padding: 6px 8px !important;
}
.ant-table-thead > tr > th {
background-color: #242542;
color: white;
}
.ant-table-thead > tr > th:hover {
background-color: #535781;
}
.ant-table-thead > tr > th.ant-table-column-has-actions.ant-table-column-has-sorters:hover {
background: rgb(201, 223, 11);
}
.ant-table-content {
background-color: #343655;
color: white;
}
.ant-table-tbody > tr:hover > td{
background-color:rgba(106, 178, 245, 0.5) ! important;
}
}
}