el-table多选框设置默认选中,翻页保留选中状态
el-table多选框设置默认选中,翻页保留选中状态
·
最近碰到个需求,el-table列表渲染数据,要求有多选框并且附带默认选中,翻页后保留选中状态
写默认选中时百度一下还很简单,但是碰到个bug,第一次翻页可以保留,第二次翻页回来之后选中的就没了。
经过研究解决,记录一下,直接上代码了
默认选中只需要给table增加
:row-key="getRowKeys"
:reserve-selection="true"
然后列表获取数据时用这个方法,我这里是默认选中row.number == 9的数据,
this.$nextTick(() => {
let table = this.tableData;
table.forEach(row => {
if (row.number == 9)
this.$refs.table.toggleRowSelection(row, true);
});
});
完整代码
<template>
<div>
<div style="width: 80%; margin: 20px auto">
<div v-for="item in multipleSelection" :key="item.id">
{{ item.name }}
</div>
<el-table
:row-key="getRowKeys"
border
ref="table"
:data="tableData"
style="width: 100%"
@selection-change="handleSelectionChange"
>
<el-table-column
:reserve-selection="true"
type="selection"
width="55"
/>
<el-table-column property="id" label="id" width="55" />
<el-table-column property="name" label="name" />
<el-table-column property="number" label="number" />
<el-table-column property="desc" label="desc" />
</el-table>
<el-pagination
:current-page="page"
:page-sizes="[10, 20, 30]"
background
layout="total, sizes, prev, pager, next, jumper"
:total="Number(totals)"
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
/>
</div>
</div>
</template>
<script>
export default {
data() {
return {
tableData: [],
multipleSelection: [],
page: 1,
pageSize: 10,
totals: ''
}
},
methods: {
SelectionChange() {
this.$nextTick(() => {
//这里把数据重新赋值一下,不然就会出现bug,从第一页翻到第二页可以保留,在回到第一页选中的就没了
let table = this.tableData;
table.forEach(row => {
if (row.number == 9)
this.$refs.table.toggleRowSelection(row, true);
});
});
},
handleSelectionChange(e) {
this.multipleSelection = e
},
// 获取列表数据
getDemoList() {
let param = {
page: this.page,
pageSize: this.pageSize
}
this.$axios.post('/api/getList', param).then((res) => {
this.tableData = res.data.data.list
this.totals = res.data.data.total
this.SelectionChange()
})
},
getRowKeys(row) {
return row.id
},
handleCurrentChange(page) {
this.page = page
this.getDemoList()
},
handleSizeChange(pageSize) {
this.pageSize = pageSize
this.getDemoList()
}
},
mounted() {
this.getDemoList()
}
}
</script>
更多推荐
已为社区贡献2条内容
所有评论(0)