公司中台項目剛開始開發,用了vue+element,需要許多前置調研,table的翻譯記憶選中就是其中之一。
template:
<el-table :ref="tableRef" :data="tableData" @select-all="handleSelect" @select="handleSelect" > <el-table-column type="selection" width="55" > </el-table-column> <el-table-column v-for="item in tableColumns" :key="item" :property="item.property" :label="item.label" :width="item.width" > </el-table-column> </el-table> <el-pagination layout="total,prev, pager, next, jumper" :page-size="5" @current-change="handleCurrentChange" :current-page.sync="currentPage" :total="10"> </el-pagination>
tableRef 是上級傳入的props,為了區分多個表格同時存在的情況。
tableData 和 tableColumns 都是從組件外傳入的,不難理解。
將 select 和 select-all 事件集中到同一個事件 handleSelect, 因為用到的數據都是該事件返回的 row 。
翻頁的 currentPage 和 handleCurrentChange 是翻頁組件的當前頁和頁碼改變的事件。
methods:
handleSelect(val){ const hasSave = this.selected.find(item => { return item.page === this.currentPage }) if(hasSave){ hasSave.rows = this.tableData.filter(item => { return val.includes(item) }) }else{ this.selected.push({ page: this.currentPage, rows: val }) } }, handleCurrentChange(val){ // 向上傳遞事件 this.$emit('pageChange',val) }, toggleSelection(){ this.$refs[this.tableRef].clearSelection() const target = this.selected.find(item => { return item.page === this.currentPage }) if(!target) return const rows = target.rows if(rows && rows.length>0){ this.$nextTick(()=>{ rows.forEach(row => { this.$refs[this.tableRef].toggleRowSelection(row) }) }) } }, getSelected(){ if(this.selected.length === 0){ return [] } let result = [] this.selected.forEach(item => { result = [...result,...item.rows] }) return result }
當頁碼改變時,傳遞數據到外層請求數據,在本組件watch tableData的變化
watch: { tableData(){ this.toggleSelection() } },
最后獲取執行具體邏輯就不解釋了,都是比較簡單的,有需要可以留言或者私信。