一、问题描述
当切换页码或者条数时,选中的数据会消失
SelectionTable.vue
<template>
<div class="selection-table">
<el-button @click="handlePrint">打印当前勾选的ids</el-button>
<el-table
ref="tableRef"
:data="tableData"
@selection-change="handleSelectionChange"
>
<el-table-column type="selection" width="55" />
<el-table-column type="index" label="序号" width="50" />
<el-table-column prop="productCategoryId" label="id" />
<el-table-column prop="nameCn" label="产品名称" />
<el-table-column prop="specsNames" label="描述" />
</el-table>
<el-pagination
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
:current-page="params.pageNo"
:page-size="11"
:page-sizes="[10, 20, 30, 40]"
layout="total, sizes, prev, pager, next, jumper"
:total="total"
/>
</div>
</template>
<script>
import { listApi } from '@/api/request'
export default {
data() {
return {
params: { pageNo: 1, pageLe: 10 },
total: 0,
tableData: [],
multipleSelection: []
}
},
created() {
this.getList()
},
methods: {
handleSelectionChange(list) {
this.multipleSelection = list
},
handlePrint() {
const ids = this.multipleSelection.map(n => n.productCategoryId)
console.log('打印当前勾选的ids', ids)
},
handleSizeChange(pageLe) {
this.params.pageNo = 1
this.params.pageLe = pageLe
this.getList()
},
handleCurrentChange(pageNo) {
this.params.pageNo = pageNo
this.getList()
},
async getList() {
try {
const { total, data } = await listApi(this.params)
console.log('请求参数', { ...this.params }, '请求结果', total, data)
this.total = total
this.tableData = data
} catch (err) {
console.log(err)
}
}
}
}
</script>
二、翻页保留数据
- 给
type
为selection
的el-table-column
添加上reserve-selection
属性 - 给
el-table
添加上:row-key="row => row.productCategoryId"
,id必须是唯一的
如此,便可以在翻页时保留数据
如果elementui版本较低,没有自动勾选上,可以在获取到接口数据后添加上:
if (this.multipleSelection.length > 0) {
this.tableData.forEach(row => {
this.multipleSelection.forEach(item => {
if (row.id === item.id) {
this.$refs.tableRef.toggleRowSelection(item, true)
}
})
})
}