在项目中经常遇到el-table的数据回显在此做个记录:
在 Element UI 的
el-dialog
中,想要实现el-table
的复选框回显(即在对话框打开时显示之前已经选中的项),需要在对话框打开之前保存选中的状态,并在打开对话框时根据这些状态来设置复选框的选中状态。
基本的实现步骤:
-
保存选中状态:在父组件中,你需要保存用户之前选中的项。这可以通过维护一个数组来实现,该数组包含所有选中的项的
id
或其他唯一标识符。 -
传递选中状态到子组件:当你打开
el-dialog
时,将这个选中状态数组传递给子组件。 -
在子组件中设置选中状态:在子组件(即
el-dialog
中的el-table
)中,监听对话框的打开事件,并在打开时根据传递的选中状态设置复选框的选中项。
##父组件
<template>
<el-button @click="openDialog">打开对话框</el-button>
<el-dialog :visible.sync="dialogVisible">
<template #default>
<el-table
:data="srpApprNoticeList"
:row-key="'id'"
@selection-change="handleSelectionChange"
>
<!-- 表格列定义 -->
<el-table-column type="selection" width="55"></el-table-column>
<!-- 其他列 -->
</el-table>
</template>
</el-dialog>
</template>
<script>
export default {
data() {
return {
dialogVisible: false,
selectedIds: [], // 保存选中的 id
srpApprNoticeList: [], // 表格数据
};
},
methods: {
openDialog() {
this.dialogVisible = true;
// 在打开对话框之前,你可以从其他地方获取选中的 id 并设置到 selectedIds
},
handleSelectionChange(selection) {
this.selectedIds = selection.map(item => item.id);
},
},
};
</script>
## 子组件
<template>
<el-dialog :visible.sync="dialogVisible">
<el-table
:data="srpApprNoticeList"
:row-key="'id'"
:default-checked-keys="selectedIds" <!-- 使用 default-checked-keys 设置默认选中 -->
>
<!-- 表格列定义 -->
<el-table-column type="selection"></el-table-column>
<!-- 其他列 -->
</el-table>
</el-dialog>
</template>
<script>
export default {
props: {
dialogVisible: Boolean,
selectedIds: Array, // 从父组件传递的选中状态
},
data() {
return {
srpApprNoticeList: [], // 表格数据
};
},
watch: {
dialogVisible(newVal) {
if (newVal) {
// 当对话框打开时,根据 selectedIds 设置复选框的选中状态
this.$nextTick(() => {
this.$refs.multipleTable.clearSelection();
this.selectedIds.forEach(id => {
const row = this.srpApprNoticeList.find(row => row.id === id);
if (row) {
this.$refs.multipleTable.toggleRowSelection(row, true);
}
});
});
}
},
},
};
</script>
父组件维护了一个
selectedIds
数组来保存选中的项的id
。当用户点击按钮打开对话框时,dialogVisible
变为true
,并且selectedIds
被传递给子组件。子组件在对话框打开时,通过watch
监听dialogVisible
的变化,并在对话框打开后设置复选框的选中状态。