HTML部分
1 <div> 2 <el-button size="small" @click="checkedAllBtn">全选</el-button> 3 <el-button size="small" @click="checkedInvertBtn">反选</el-button> 4 </div> 5 <el-table 6 ref="table" 7 :data="tableData" 8 v-loading="loading" 9 tooltip-effect="dark" 10 style="width: 100%" 11 @selection-change="handleSelectionChange" 12 > 13 <el-table-column type="selection" width="55"></el-table-column> 14 </el-table>
定义data
data() { return { loading: true,
id: 'id', tableData: [], checkedDataAll: [], // 所有选中的数据 multipleChecked: [], // 当前页选中的数据 } },
页面初始化
1 mounted() { 2 this.init() 3 }
1 init() { 2 axios({ ... }).then((res) => { 3 this.setSelectRow(this.id, this.checkedDataAll, this.tableData, 'table') 4 }); 5 }
实现方法
1 handleSelectionChange(rows) { 2 if (rows) { 3 this.multipleChecked = rows 4 } 5 this.$nextTick(() => { 6 this.changePageData(this.id) 7 }) 8 },
1 changePageData(id) { // 记录翻页后的数据 2 if (this.checkedDataAll.length <= 0) { 3 this.checkedDataAll = this.multipleChecked 4 return 5 } 6 7 let selectAllIds = [] // 所有页选中的ids 8 let selectIds = [] // 当前页选中的ids 9 let noSelectIds = [] // 当前页没有选中的ids 10 11 this.checkedDataAll.map(item => { 12 selectAllIds.push(item[id]) 13 }) 14 this.multipleChecked.map(item => { 15 selectIds.push(item[id]) 16 if (selectAllIds.indexOf(item[id]) < 0) { 17 this.checkedDataAll.push(item) 18 } 19 }) 20 this.tableData.map(item => { 21 if (selectIds.indexOf(item[id]) < 0) { 22 noSelectIds.push(item[id]) 23 } 24 }) 25 noSelectIds.map(item => { 26 if (selectAllIds.indexOf(item) >= 0) { 27 for (let i = 0; i < this.checkedDataAll.length; i++) { 28 if (this.checkedDataAll[i][id] === item) { 29 this.checkedDataAll.splice(i, 1) 30 break 31 } 32 } 33 } 34 }) 35 },
1 // 设置选中项 2 setSelectRow(id, checkedAllData, tableData, tableName) { 3 this.$nextTick(() => { 4 if (!checkedAllData || checkedAllData.length <= 0) { 5 this.$refs[tableName].clearSelection() 6 return 7 } 8 9 let selectAllIds = [] 10 checkedAllData.map(item => { 11 selectAllIds.push(item[id]) 12 }) 13 this.$refs[tableName].clearSelection() 14 for (let i = 0; i < tableData.length; i++) { 15 if (selectAllIds.indexOf(tableData[i][id]) >= 0) { 16 this.$refs[tableName].toggleRowSelection(tableData[i], true) // 设置勾选 17 } else { 18 this.$refs[tableName].toggleRowSelection(tableData[i], false) // 取消勾选 19 } 20 } 21 }) 22 },
全选按钮 请求拿到所有的数据
1 checkedAllBtn() { 2 axios({ ... }).then((res) => { 3 this.checkedDataAll = res.data.records 4 this.setSelectRow(this.id, this.checkedDataAll, this.tableData, 'table') 5 }) 6 }
反选按钮 遍历所有的数据进行反向选择
1 checkedInvertBtn() { 2 let selectAllIds = [] 3 this.checkedDataAll.map(item => { 4 selectAllIds.push(item['id']) 5 }) 6 axios({ ... }) 7 .then((res) => { 8 this.checkedDataAll = [] 9 res.data.records.map(item => { 10 if (selectAllIds.indexOf(item['id']) < 0) { 11 this.checkedDataAll.push(item) 12 } 13 }) 14 this.setSelectRow(this.id, this.checkedDataAll, this.tableData, 'table') 15 }) 16 17 }