シナリオ: データ テーブル内のデータを選択し、データ操作を保存します。
データ テーブルの場合、この要件はあまり一般的ではないようです。少量のデータの場合はチェックボックスで要件を満たすのに十分ですが、大量のデータの場合は、選択を行うためにテーブルを使用する必要があることがよくあります。
にはそのような属性el-table
がありますTable-column Attributes
:
属性 | 説明する | タイプ | オプションの値 | デフォルト |
---|---|---|---|---|
予備選択 | これは、type=selection の列に対してのみ有効です。タイプは Boolean です。true の場合、データが更新された後も、以前に選択されたデータが保持されます (行キーを指定する必要があります)。 | ブール値 | — | 間違い |
ただし、行のキーを指定する必要があるため、属性el-table
を追加してrow-key
キーを指定できます。
最終的なコードは次のとおりです
<template>
<el-table ref="dataTable" :data="tableList" :row-key="getRowKeys" border>
<el-table-column type="selection" width="55" reserve-selection></el-table-column>
</el-table>
</template>
<script>
export default {
data() {
return {
tableList: []
}
},
methods: {
// 获取行的key,用于表格保留分页选中
getRowKeys(row) {
return row.id;
}
}
}
</script>
以下に、複数の選択をページングし、最初の選択を割り当てるためのソリューションを示します。
<template>
<el-table ref="dataTable" :data="tableList" :row-key="getRowKeys" @select="handleSelectionChange" border>
<el-table-column type="selection" reserve-selection></el-table-column>
</el-table>
</template>
<script>
import service from './service'
export default {
data() {
return {
tableList: [], // 表格数据
defaultSelectedIds: [], // 默认选中数据ID
multipleSelection: [] // 选中的所有行数据
}
},
methods: {
// 获取行的key,用于表格保留分页选中
getRowKeys(row) {
return row.id;
},
handleSelectionChange(selection, row) {
// 判断如果是取消选中,且在defaultSelectedIds中含有的,则删掉
const index = this.defaultSelectedIds.indexOf(row.id);
if (this.multipleSelection.length > selection.length && index !== -1) {
this.defaultSelectedIds.splice(index, 1);
}
this.multipleSelection = selection;
},
getTableList() {
service.getDataList().then(res => {
this.tableList = res.list;
// 判断在defaultSelectedIds中含有的,通过方法去选中,保留defaultSelectedIds是因为defaultSelectedIds中的值无法对全部页选中
this.$nextTick(() => {
if (this.tableList && this.defaultSelectedIds) {
this.tableList.forEach(row => {
if (this.defaultSelectedIds.includes(row.id)) {
this.multipleSelection.push(row);
this.$refs.dataTable.toggleRowSelection(row, true);
}
});
}
});
});
}
}
}
</script>