elementui 表格全选当前页,全选所有数据
时间: 2023-10-17 08:08:11 浏览: 121
Element实现表格分页数据选择+全选所有完善批量操作
您好,您可以通过以下代码实现ElementUI表格全选当前页和全选所有数据:
```html
<template>
<el-table :data="tableData" style="width: 100%">
<el-table-column type="selection" :selectable="selectable" />
<el-table-column prop="date" label="日期" width="180" />
<el-table-column prop="name" label="姓名" width="180" />
<el-table-column prop="address" label="地址" />
</el-table>
<div style="margin-top: 20px;">
<el-button @click="handleSelectAll(true)">全选当前页</el-button>
<el-button @click="handleSelectAll(false)">取消全选</el-button>
<el-button @click="handleSelectAll(true, 'all')">全选所有数据</el-button>
</div>
</template>
<script>
export default {
data() {
return {
tableData: [
{
date: '2020-07-10',
name: '张三',
address: '北京市'
},
{
date: '2020-07-11',
name: '李四',
address: '上海市'
},
{
date: '2020-07-12',
name: '王五',
address: '广州市'
},
{
date: '2020-07-13',
name: '赵六',
address: '深圳市'
}
],
selectable: (row, index) => {
return index !== 3; // 只有前三行可选
},
selectedRows: []
};
},
methods: {
// 全选当前页
handleSelectAll(checked, type = 'page') {
if (checked) {
const rows = this.$refs.table[state].tableData;
const selectedRows = rows.filter(row => row.$selectable !== false);
const selection = selectedRows.filter(row => {
const isSelected = this.selectedRows.some(item => item === row);
return !isSelected;
});
this.selectedRows = [...this.selectedRows, ...selection];
} else {
this.selectedRows = this.selectedRows.filter(row => row.$selectable !== false);
}
const selection = this.selectedRows.map(row => row.$index);
this.$refs.table[type === 'all' ? 'table' : 'bodyWrapper']
.querySelectorAll('.el-table__body-wrapper > table > tbody > tr')
.forEach((row, index) => {
const $row = this.$refs.table.$getRow(index);
if ($row.$selectable === false) return;
if (checked) {
if (!this.selectedRows.some(i => i.$index === $row.$index)) {
$row.classList.add('selected');
this.selectedRows.push($row);
}
} else {
$row.classList.remove('selected');
const selectionIndex = selection.indexOf(index);
if (selectionIndex !== -1) {
this.selectedRows.splice(selectionIndex, 1);
}
}
});
}
}
};
</script>
```
在这个例子中,我们使用了`el-table-column`组件的`type="selection"`属性来给表格加上复选框列,通过`selectable`属性来控制行是否可选。然后,我们在模板中添加了三个按钮,分别用来全选当前页、取消全选以及全选所有数据。在`handleSelectAll`方法中,我们通过`querySelectorAll`和`$getRow`方法来获取所有行,然后再根据行的`$selectable`值来判断该行是否可选。最后,我们利用`classList`来动态添加或移除`selected`类和记录选中的行。
阅读全文