el-table表格并沒有相關的方法來禁用表頭里面的多選按鈕
那么我們可以另辟蹊徑,來實現相同的多選+切換分頁(保留分頁數據)+ 限制多選數量的效果
<el-table:data="tableData"style="width: 100%">// 不使用el-talbe自帶的多選功能//<el-table-column type="selection" width="55"></el-table-column>//自己單獨建一個el-table-column 來設置選中狀態<el-table-column fixed width="60"><template slot-scope="scope"><el-checkbox v-model="scope.row.isCheck":disabled="selectable(scope.row)"@change="checkChange($event, scope.$index, scope.row)"></el-checkbox></template></el-table-column><el-table-columnlabel="日期"width="120"><template slot-scope="scope">{{ scope.row.date }}</template></el-table-column>
</el-table>
//在獲取表格數據以后 遍歷表格,為每行數據添加上 isCheck 屬性,并設置默認值false
this.tableData.forEach(item =>{item.isCheck = false;
})
實現多選功能 checkChange
//事件有三個參數 // val el-checkbox change事件返回的值 代表 選中/不選中// index 當前tableData 所在的行// row 當前tableData 當前行的數據checkChange(val, index, row) {//通過val true/false ;來判斷是 選中當前行/取消選中當前行if (val) {//選中 往多選數組里面推送this.multipleSelection.push(row);} else {//取消選中(刪除) 拿到當前數據的唯一標識id const { id } = row;let delIndex = this.multipleSelection.findIndex((item) => item.id=== id);//刪除 取消選中的數據if (delIndex !== -1) {this.multipleSelection.splice(delIndex, 1);}}//重新設置 表格當前行的多選狀態this.$set(this.tableData, index, { ...row, isCheck: !!val });},
實現 限制多選數量的功能 selectable(scope.row)
//我們在最上面的實例中定義了一個 el-checkbox的禁用方法 :disabled="selectable(scope.row)"//限制最多只能選擇5個
// 方法返回 true/false 來實現el-checkbox的禁用/選中功能
selectable(row) {//限制多選最多只能選擇5個let limitNum = 5let ids = this.multipleSelection.map((item) => item.id);//判斷當前行的唯一標識符 id,是否存在于多選數組中if (ids.includes(row.id)) {// 已選擇的行,可取消禁用return false;} else if (ids.length >= limitNum && !ids.includes(row.coilNo)) {// 超過最大選擇條數,且當前行未被選中時,禁用return true;} else {// 其他情況下可選 取消禁用return false;}
}
實現切換分頁保留分頁數據功能
//獲取表格數據
getTableData(){//模擬數據獲取this.tableData = res.data || []//判斷選中數組是否有值 有值(執行回顯選中數據功能)if (this.multipleSelection.length > 0) {this.echoMultiple();}
}//回顯多選值
echoMultiple() {//增加校驗 如果當前tableData沒有值 就不回顯選中數據if (this.multipleSelection.length === 0 || this.tableData.length === 0) {return;}let ids = this.multipleSelection.map((item) => item.id) || [];this.tableData.forEach((item, index) => {//遍歷 tableData數值 找出符合要求的idif (ids.includes(item.id)) {// 為符合回顯要求的數據 設置選中狀態this.$set(this.tableData, index, { ...item, isCheck: true });}});//避免視圖不刷新 強制刷新視圖this.$forceUpdate();}