vue3 elementplus table表格内添加checkbox和行号
1.仅添加复选框
<el-table :data="tableData" style="width: 100%" ref="table" @selection-change="selectionLineChangeHandle" @row-dblclick="bannerEdit($event)">
1 | <el-table-column type= "selection" width= "55" ></el-table-column> |
</el-table>
1.1监听选中框
const selectionLineChangeHandle = (e) => { const ids = []; e.forEach((e) => { ids.push(e.id); }); idList.value = ids; };
2.添加复选框和文字行号在一列(组件形式)
<template>
<el-table-column width="80px">
<template #header>
<el-checkbox v-model="selectAll" @change="handleSelectAll">全选</el-checkbox>
</template>
<template #default="{$index,row}">
<el-checkbox v-model="selectedRows[$index]" @change="CheckOption(row)"></el-checkbox>
<span>{{$index+1}}</span>
</template>
</el-table-column>
</template>
<script setup>
import { ref } from "vue";
const selectedRows = ref([]);
const idList = ref([]); //选中行id集合
// 接收父组件传递数据
const props = defineProps({
tableData: {},//所传值为对象
});
const emit = defineEmits(["update:tableData",'delete']);
// const emit = defineEmits(['delete']);
//监听全选
const selectAll = ref(false);
const handleSelectAll = () => {
const rowNum=[];
if (!selectAll.value) {
idList.value = [];
for (var i = 0; i < selectedRows.value.length; i++) {
selectedRows.value[i] = false;
}
} else {
props.tableData.forEach((item, index) => {
rowNum.push(`${index}`);
});
const ids = [];
for (var i = 0; i < rowNum.length; i++) {//i的值和rowNum里面的值一样故可以省略
if (props.tableData[i]) {
ids.push(props.tableData[i].id);
selectedRows.value[i] = true;
}
}
idList.value = ids;
}
};
// 监听选中行
const CheckOption = (row) => {
const ids = [];
// 点击的行(只要点击过都会录入,不管最后是否选中)
const rowNum = Object.keys(selectedRows.value);
for (var i = 0; i < rowNum.length; i++) {
if (Object.values(selectedRows.value)[i]) {
ids.push(props.tableData[rowNum[i]].id); //rowNum必写
}
}
idList.value = ids;
const CheckNumber = idList.value.length; //选中数
const TotalNumber = props.tableData.length; //总行数
// 比较选中行数 和总行数
if (CheckNumber < TotalNumber) {
selectAll.value = false;
} else {
selectAll.value = true;
}
};
// 删除选中行
const deleteSelectedRow = async (deleteAccountCop) => {
const data = idList.value;
if (data[0] == undefined) {
ElMessage({
type: "error",
message: "请在要选择的行首选择确认!",
duration: 5000,
});
} else {
ElMessageBox.confirm("确定要删除吗", "Warning", {
confirmButtonText: "确定",
cancelButtonText: "取消",
type: "warning",
}).then(async () => {
emit('delete', data)
});
}
};
defineExpose({
deleteSelectedRow
})
</script>