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 }