直接看代码
<template>
<div>
<el-table
ref="multipleTable"
:data="tableData"
tooltip-effect="dark"
style="width: 100%;height:500px"
@select="handleSelectChange"
@select-all="handleSelectAllChange"
row-key="id"
>
<!-- reserve-selection 可以不要 但是就没有分页半选状态 没有的话 下handleSelectAllChange部分代码可以不要-->
<el-table-column
type="selection"
width="55"
reserve-selection
/>
<el-table-column
label="日期"
width="120"
prop="date"
/>
<el-table-column
prop="name"
label="姓名"
width="120"
/>
</el-table>
<el-pagination
background
:current-page.sync="currentPage"
layout="prev, pager, next"
:total="1000"
@current-change="currentChange"
/>
</div>
</template>
<script>
export default {
data () {
return {
currentPage: 1,
crossPageMap: new Map(),
pageSize: 10,
totalData: Array.from({ length: 1000 }, (_, index) => {
return {
date: '2016-05-03',
id: index,
name: '王小虎' + index
}
})
}
},
computed: {
tableData () {
const { currentPage, totalData, pageSize } = this
return totalData.slice((currentPage - 1) * pageSize, currentPage * pageSize)
},
},
methods: {
currentChange (page) {
this.currentPage = page
this.search()
},
handleSelectChange (val, row) {
const checked = this.crossPageMap.has(row.id)
if (checked) {
this.crossPageMap.delete(row.id)
} else {
this.crossPageMap.set(row.id, row)
}
},
handleSelectAllChange (val) {
this.tableData.forEach(row => {
const isChecked = this.crossPageMap.has(row.id)
if (val.length === 0) {
// 取消全选 只有选中的需要改变状态
if (isChecked) this.crossPageMap.delete(row.id)
} else {
// 全选
// 因为有reserve-selection 所以会返回其他页的数据 如果val里面没有当前页的数据 就删除 如果没有reserve-selection 则不需要这行循环的代码
// reserve-selection 可以让分页的全选按钮保留半选状态
if(val.findIndex(ele => ele.id == row.id) == -1){
this.crossPageMap.delete(row.id)
}
//如果没有选中就添加
if (!isChecked) this.crossPageMap.set(row.id,row)
}
})
},
search(){
this.tableData.forEach(row => {
const checked = this.crossPageMap.has(row.id)
if (checked) this.$refs.multipleTable.toggleRowSelection(row, true)
})
// this.crossPageMap 请注意,无法响应式 计算属性也不行 有黑科技可以在计算属性里面用一个其他的属性收集依赖 每次选中项变化时修改这个属性,
// 就可以进行触发 如果需要页面展示选中的数据 可以研究一下发个链接参考参考
console.log(Array.from(this.crossPageMap.values()));
}
},
mounted(){
this.$nextTick(()=>{
this.$refs.multipleTable.clearSelection()
// 默认选中项目
let defaultChecked = [{ id: 13},{id: 3}]
defaultChecked.forEach(ele => {
this.crossPageMap.set(ele.id, ele)
})
this.search()
})
}
}
</script>
注意reserve-selection用法
相关代码借鉴掘金 链接找不到了