Element-ui el-table元件實現跨頁選中
阿新 • • 發佈:2019-01-11
首先定義data
data () {
return {
multipleSelectionAll: [], // 所有選中的資料包含跨頁資料
multipleSelection: [], // 當前頁選中的資料
idKey: 'personId', // 標識列表資料中每一行的唯一鍵的名稱(需要按自己的資料改一下)
tableData: [] // 表格資料
// 此處省略pagination的定義
}
}
然後是方法
methods : { // 設定選中的方法 setSelectRow() { if (!this.multipleSelectionAll || this.multipleSelectionAll.length <= 0) { return; } // 標識當前行的唯一鍵的名稱 let idKey = this.idKey; let selectAllIds = []; let that = this; this.multipleSelectionAll.forEach(row=>{ selectAllIds.push(row[idKey]); }) this.$refs.table.clearSelection(); for(var i = 0; i < this.tableData.length; i++) { if (selectAllIds.indexOf(this.tableData[i][idKey]) >= 0) { // 設定選中,記住table元件需要使用ref="table" this.$refs.table.toggleRowSelection(this.tableData[i], true); } } } , // 記憶選擇核心方法 changePageCoreRecordData () { // 標識當前行的唯一鍵的名稱 let idKey = this.idKey; let that = this; // 如果總記憶中還沒有選擇的資料,那麼就直接取當前頁選中的資料,不需要後面一系列計算 if (this.multipleSelectionAll.length <= 0) { this.multipleSelectionAll = this.multipleSelection; return; } // 總選擇裡面的key集合 let selectAllIds = []; this.multipleSelectionAll.forEach(row=>{ selectAllIds.push(row[idKey]); }) let selectIds = [] // 獲取當前頁選中的id this.multipleSelection.forEach(row=>{ selectIds.push(row[idKey]); // 如果總選擇裡面不包含當前頁選中的資料,那麼就加入到總選擇集合裡 if (selectAllIds.indexOf(row[idKey]) < 0) { that.multipleSelectionAll.push(row); } }) let noSelectIds = []; // 得到當前頁沒有選中的id this.tableData.forEach(row=>{ if (selectIds.indexOf(row[idKey]) < 0) { noSelectIds.push(row[idKey]); } }) noSelectIds.forEach(id=>{ if (selectAllIds.indexOf(id) >= 0) { for(let i = 0; i< that.multipleSelectionAll.length; i ++) { if (that.multipleSelectionAll[i][idKey] == id) { // 如果總選擇中有未被選中的,那麼就刪除這條 that.multipleSelectionAll.splice(i, 1); break; } } } }) }, currentChange(val){ // 改變頁的時候呼叫一次 this.changePageCoreRecordData(); this.pagination.pageNumber = val; this.query(); }, sizeChange(val){ // 改變每頁顯示條數的時候呼叫一次 this.changePageCoreRecordData(); this.pagination.pageSize = val; this.query(); }, handleSelectionChange (val) { // table元件選中事件,記得加上@selection-change="handleSelectionChange" this.multipleSelection = val; }, query () { // 分頁查詢資料方法,在成功返回資料方法裡呼叫setSelectRow方法,使每次分頁查詢都能勾選中 $.ajax({..., success:(res)=>{ ...... setTimeout(()=>{ this.setSelectRow(); }, 200) } }) }, // 得到選中的所有資料 getAllSelectionData () { // 再執行一次記憶勾選資料匹配,目的是為了在當前頁操作勾選後直接獲取選中資料 this.changePageCoreRecordData(); console.log(this.multipleSelectionAll) } }
如果你的是自定義元件dialog彈窗裡面的表格選擇,如果想每次開啟想選中,那麼就直接在props加一個值,然後加一個watch
props: [ "selectData"],
watch: {
'selectData' (val) {
this.multipleSelectionAll = val;
}
},