ElementUI Table组件,选择多行数据时使用 Checkbox。如下图:
但是业务中,表格数据往往不只一页。多页数据情况下,表格勾选某些行,就会遇到返回上一页,勾选消失的情况。这种情况,需要一些技巧和处理。具体代码如下:
<template>
<div class="demo-example">
<el-table
ref="table"
v-loading="loading"
:data="list"
height="650"
border
@select="onSelect"
@select-all="onSelectAll"
@selection-change="onSelectionChange"
>
<el-table-column type="selection" width="55"></el-table-column>
<el-table-column prop="u_createTime" label="注册时间"></el-table-column>
<el-table-column prop="u_id" label="用户ID"></el-table-column>
<el-table-column prop="u_nickname" label="用户名称"></el-table-column>
<el-table-column prop="u_phone" label="用户账户"></el-table-column>
<el-table-column prop="u_gender" label="性别"></el-table-column>
<el-table-column label="角色">
<template slot-scope="scope">
<span>{{scope.row.u_role === 1 ? '团队长' : '保险人'}}</span>
</template>
</el-table-column>
<el-table-column prop="u_companyNum" label="所属企业数量"></el-table-column>
<el-table-column prop="ha_addPeople" label="所属群组">
<template slot-scope="scope">
<el-button @click="onChakan(scope.row)" type="text" style="color:#67c23a" size="small">查看</el-button>
</template>
</el-table-column>
<el-table-column prop="u_lastLoginTime" label="最近登录时间"></el-table-column>
</el-table>
<div class="block pag" v-if="total">
<el-pagination
@current-change="onChangePage"
:current-page="currentPage"
:page-size="10"
layout="total, prev, pager, next, jumper"
:total="total"
></el-pagination>
</div>
</div>
</template>
<script>
export default {
data() {
return {
selections: {}, // 保存已选择过的row
list: [],
total: 0,
curPage: 1,
};
},
//方法事件
methods: {
// 勾选时候,记录[{u_id: row}, ...]
onSelect(selection, row) {
if (this.selections[row.u_id]) {
delete this.selections[row.u_id];
} else {
this.selections[row.u_id] = row;
}
},
// 全选情况
onSelectAll(selection) {
// 全选
if (selection.length) {
selection.forEach(row => {
this.selections[row.u_id] = row;
})
} else {
// 取消全选
this.list.forEach(row => {
delete this.selections[row.u_id];
})
}
},
// 对已选择过的row勾选,返回到上一页时候
checkRows() {
const keys = Object.keys(this.selections);
const rows = this.list.filter(row => {
return keys.includes(String(row.u_id));
});
rows.map(row => {
this.$refs.table.toggleRowSelection(row);
});
},
// 省略...
// 获取数据列表
getData() {
// ...
},
},
created() {
this.getData();
}
};
</script>
现在分页切换,勾选依然会显示,对应每页勾选过的行数据。需要提交的勾选数据,也都在this.selections
对象中。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。