真实项目数据格式:接口数据如下真实展示, 加载角色列表的选中项(根据后台返回的id),以及用户点击选中的项处理
<template>
<el-scrollbar class="scrolbar-wrapper">
<el-table
ref="table"
:data="apiObj"
@select="(selection,row)=>{selectionChange(selection,row)}" // select当用户手动勾选数据行的 Checkbox 时触发的事件
stripe
remoteSort
remoteFilter
>
<el-table-column type="selection" width="100"></el-table-column>
<el-table-column label="#" type="index" width="100"></el-table-column>
<el-table-column label="角色" prop="remark"></el-table-column>
</el-table>
</el-scrollbar>
</template>
<style scoped>
.scrolbar-wrapper{
height: 300px;
}
</style>
接口数据格式:
{code: "2000", msg: "操作成功",…}
code: "2000"
data: [{createBy: "LIWENYI245", createTime: "2022-01-17 14:27:18", updateBy: "GAOLIANG356",…},…]
0: {createBy: "LIWENYI245", createTime: "2022-01-17 14:27:18", updateBy: "GAOLIANG356",…}
1: {createBy: "LIWENYI245", createTime: "2022-01-17 14:40:27", updateBy: "GAOLIANG356",…}
2: {createBy: "LIWENYI245", createTime: "2022-01-17 14:41:45", updateBy: "umrunner",…}
msg: "操作成功"
处理接口处理
// 获取角色选择框列表
async getOptionSelect() {
const result = await this.$API.system.role.optionSelect.post();
this.apiObj = result.data; // 给表格的数据源
this.loadData(result.data);
},
// 加载角色列表的选中项
loadData(dataTable) {
this.$nextTick(() => {
dataTable.forEach((row) => { // hasSelectList已选择的id组成的数组
if (this.hasSelectList.indexOf(row.roleId) >= 0) {
// toggleRowSelection(row, selected)接受两个参数,row传递被勾选行的数据,selected设置是否选中
this.$refs.table.toggleRowSelection(row, true);
}
});
});
},
//用户手动勾选时,触发事件
selectionChange(selection, row) {
this.selection = selection;
if (this.hasSelectList.includes(row.roleId)) {
//包含返回true, hasSelectList已选择的id组成的数组
this.hasSelectList.splice(this.hasSelectList.indexOf(row.roleId), 1); // 匹配到的下标,删除1项
} else {
this.hasSelectList.push(row.roleId);
}
},
//includes() 方法用来判断一个数组是否包含一个指定的值,根据情况,如果包含则返回 true,否则返回false。
//splice() 方法通过删除或替换现有元素或者原地添加新的元素来修改数组,并以数组形式返回被修改的内容。此方法会改变原数组
//Splice指定两个参数,要删除的第一项的位置和要删除项的项数。
//indexOf()方法返回在数组中可以找到一个给定元素的第一个索引,如果不存在,则返回-1。