vue ant design表格checkbox全选
时间: 2023-06-30 13:16:29 浏览: 187
ant design的table组件实现全选功能以及自定义分页
在 Ant Design 的表格中,可以使用 `Checkbox` 组件来实现全选功能。以下是一个简单的实现示例:
1. 在表格的列定义中添加一个 `render` 函数,用于渲染 `Checkbox` 组件:
```javascript
const columns = [
{
title: '姓名',
dataIndex: 'name',
},
{
title: '年龄',
dataIndex: 'age',
},
{
title: '操作',
render: (text, record) => (
<Checkbox onChange={handleSelect(record.key)} />
),
},
];
```
2. 在表格上面添加一个 `Checkbox` 组件,用于触发全选操作:
```javascript
const handleSelectAll = (e) => {
setData(
data.map((item) => {
return {
...item,
selected: e.target.checked,
};
})
);
};
return (
<div>
<Checkbox onChange={handleSelectAll}>全选</Checkbox>
<Table
columns={columns}
dataSource={data}
rowSelection={{
selectedRowKeys: selectedKeys,
onChange: handleSelectChange,
}}
/>
</div>
);
```
3. 在 `handleSelect` 函数中更新选中状态,并根据选中状态更新全选状态:
```javascript
const handleSelect = (key) => (e) => {
setData(
data.map((item) => {
if (item.key === key) {
return {
...item,
selected: e.target.checked,
};
}
return item;
})
);
const selectedAll = data.every((item) => item.selected);
setSelectedAll(selectedAll);
};
```
完整的示例代码:
```javascript
import React, { useState } from 'react';
import { Table, Checkbox } from 'antd';
const data = [
{
key: '1',
name: 'John Brown',
age: 32,
selected: false,
},
{
key: '2',
name: 'Jim Green',
age: 42,
selected: false,
},
{
key: '3',
name: 'Joe Black',
age: 32,
selected: false,
},
];
const Demo = () => {
const [selectedAll, setSelectedAll] = useState(false);
const [selectedKeys, setSelectedKeys] = useState([]);
const handleSelectAll = (e) => {
setData(
data.map((item) => {
return {
...item,
selected: e.target.checked,
};
})
);
setSelectedAll(e.target.checked);
setSelectedKeys(e.target.checked ? data.map((item) => item.key) : []);
};
const handleSelectChange = (selectedRowKeys) => {
setSelectedKeys(selectedRowKeys);
setSelectedAll(selectedRowKeys.length === data.length);
};
const handleSelect = (key) => (e) => {
setData(
data.map((item) => {
if (item.key === key) {
return {
...item,
selected: e.target.checked,
};
}
return item;
})
);
const selectedAll = data.every((item) => item.selected);
setSelectedAll(selectedAll);
setSelectedKeys(
data.filter((item) => item.selected).map((item) => item.key)
);
};
const columns = [
{
title: '姓名',
dataIndex: 'name',
},
{
title: '年龄',
dataIndex: 'age',
},
{
title: '操作',
render: (text, record) => (
<Checkbox onChange={handleSelect(record.key)} />
),
},
];
return (
<div>
<Checkbox onChange={handleSelectAll} checked={selectedAll}>
全选
</Checkbox>
<Table
columns={columns}
dataSource={data}
rowSelection={{
selectedRowKeys: selectedKeys,
onChange: handleSelectChange,
}}
/>
</div>
);
};
export default Demo;
```
阅读全文