最近做了一个小需求,个人记录一下,实现效果大概如下!
不多唠了直接贴码
<template>
<div class="box">
<h2>vue Antd(table结合Checkbox)实现可选择表头</h2>
<h2>-</h2>
<h2>-</h2>
<h2>-</h2>
<div class="inpBox">
<a-popover placement="topLeft">
<template slot="content">
<a-checkbox-group v-model="checkedList" @change="changeList">
<a-checkbox
v-for="(item, index) in list"
:key="index"
:value="item"
>{{ item }}</a-checkbox
>
</a-checkbox-group>
</template>
<a-icon
type="appstore"
style="fontsize: 24px; border: 1px solid #ccc; padding: 5px 5px"
/>
</a-popover>
</div>
<a-table :columns="filterColumns" :data-source="data">
<a slot="name" slot-scope="text">{{ text }}</a>
</a-table>
</div>
</template>
<script>
export default {
data() {
return {
// 表头选项
list: ["表头1", "表头2", "表头3", "表头4", "表头5", "表头6"],
// 表头已选项(需要和【可配置表头信息】filterColumns数量保持一致,如不一致会出现展示问题。很重要)
checkedList: ["表头1", "表头2"],
//全部表头信息
columns: [
{
title: "表头1",
dataIndex: "name",
key: "name",
scopedSlots: { customRender: "name" },
},
{
title: "表头2",
dataIndex: "age",
key: "age",
width: 80,
},
{
title: "表头3",
dataIndex: "addressA",
key: "addressA",
ellipsis: true,
},
{
title: "表头4",
dataIndex: "addressB",
key: "addressB",
ellipsis: true,
},
{
title: "表头5",
dataIndex: "addressC",
key: "addressC",
ellipsis: true,
},
{
title: "表头6",
dataIndex: "address",
key: "address 3",
ellipsis: true,
},
],
//可配置表头信息(需要和【表头已选项】checkedList数量保持一致,如不一致会出现展示问题。很重要)
filterColumns: [
{
title: "表头1",
dataIndex: "name",
key: "name",
scopedSlots: { customRender: "name" },
},
{
title: "表头2",
dataIndex: "age",
key: "age",
width: 80,
},
],
// data
data: [
{
key: "1",
name: "John Brown",
age: 32,
address: "New York No. 1 Lake Park, New York No. 1 Lake Park",
tags: ["nice", "developer"],
},
{
key: "2",
name: "Jim Green",
age: 42,
address: "London No. 2 Lake Park, London No. 2 Lake Park",
tags: ["loser"],
},
{
key: "3",
name: "Joe Black",
age: 32,
address: "Sidney No. 1 Lake Park, Sidney No. 1 Lake Park",
tags: ["cool", "teacher"],
},
],
};
},
methods: {
// 联动
changeList() {
this.filterColumns = this.columns.filter((item, index) => {
// 主要通过checkedList里的已选项返回对应的表头
return this.checkedList.includes(item.title);
});
},
},
};
</script>
<style>
.box {
width: 100%;
}
.inpBox {
width: 800px;
display: flex;
flex-direction: row;
margin: 0 auto;
align-items: center;
}
</style>