vue3使用el-table怎么实现全选删除
时间: 2023-06-26 12:07:33 浏览: 131
实现 Vue3 中 ElTable 全选删除可以分为以下几个步骤:
1. 添加全选 checkbox。在 ElTable 上方添加一个 checkbox,用于全选/取消全选。
```
<template>
<div>
<el-table :data="tableData" style="width: 100%">
<el-table-column type="selection"></el-table-column>
<el-table-column prop="name" label="Name"></el-table-column>
<el-table-column prop="age" label="Age"></el-table-column>
<el-table-column prop="address" label="Address"></el-table-column>
</el-table>
<div>
<el-checkbox v-model="checkedAll" @change="handleCheckAllChange">
Check All
</el-checkbox>
</div>
</div>
</template>
```
2. 监听全选 checkbox 变化。使用 `v-model` 绑定全选 checkbox 的状态,在 `@change` 事件中修改每行数据的 `checked` 属性。
```
<script>
import { ref } from 'vue';
export default {
setup() {
const tableData = ref([
{
id: 1,
name: 'John',
age: 18,
address: 'New York',
checked: false,
},
{
id: 2,
name: 'Amy',
age: 22,
address: 'Los Angeles',
checked: false,
},
{
id: 3,
name: 'Bob',
age: 30,
address: 'Chicago',
checked: false,
},
]);
const checkedAll = ref(false);
const handleCheckAllChange = (value) => {
tableData.value.forEach((item) => {
item.checked = value;
});
};
return {
tableData,
checkedAll,
handleCheckAllChange,
};
},
};
</script>
```
3. 实现删除功能。添加一个删除按钮,点击后删除选中的行数据。
```
<template>
<div>
<el-table :data="tableData" style="width: 100%">
<el-table-column type="selection"></el-table-column>
<el-table-column prop="name" label="Name"></el-table-column>
<el-table-column prop="age" label="Age"></el-table-column>
<el-table-column prop="address" label="Address"></el-table-column>
<el-table-column>
<template #default="{ row }">
<el-button type="danger" size="mini" @click="handleDelete(row)">
Delete
</el-button>
</template>
</el-table-column>
</el-table>
<div>
<el-checkbox v-model="checkedAll" @change="handleCheckAllChange">
Check All
</el-checkbox>
<el-button type="danger" @click="handleDeleteAll">Delete All</el-button>
</div>
</div>
</template>
<script>
import { ref } from 'vue';
export default {
setup() {
const tableData = ref([
{
id: 1,
name: 'John',
age: 18,
address: 'New York',
checked: false,
},
{
id: 2,
name: 'Amy',
age: 22,
address: 'Los Angeles',
checked: false,
},
{
id: 3,
name: 'Bob',
age: 30,
address: 'Chicago',
checked: false,
},
]);
const checkedAll = ref(false);
const handleCheckAllChange = (value) => {
tableData.value.forEach((item) => {
item.checked = value;
});
};
const handleDelete = (row) => {
const index = tableData.value.indexOf(row);
tableData.value.splice(index, 1);
};
const handleDeleteAll = () => {
const checkedItems = tableData.value.filter((item) => item.checked);
checkedItems.forEach((item) => {
const index = tableData.value.indexOf(item);
tableData.value.splice(index, 1);
});
};
return {
tableData,
checkedAll,
handleCheckAllChange,
handleDelete,
handleDeleteAll,
};
},
};
</script>
```
这样就完成了 Vue3 中 ElTable 的全选删除功能。
阅读全文