element-ui 中table 組件不帶有分頁(yè)较木,必須配合pagination組件來(lái)完成表格的分頁(yè)功能篙程,這對(duì)列表頁(yè)面很多的系統(tǒng)來(lái)說(shuō)锌畸,每次都需要定義分頁(yè)組件相關(guān)的屬性和事件蝙砌,似乎做了很多重復(fù)的工作叉跛。下面通過(guò)寫(xiě)一個(gè)擴(kuò)展組建來(lái)把table和pagination組件封裝起來(lái)松忍。
//table.js
import { Table, Pagination } from 'element-ui';
import Vue from 'vue';
export default {
name: 'ExTable',
mixins: [Table],
props: {
showPagination: {
type: Boolean,
default: true
},
pager_layout: {
type: String,
default: 'total,sizes,prev, pager, next, jumper'
},
pageSize: {
type: Number,
default: 10
},
pageSizes: {
type: Array,
default: () => [10, 25, 50, 100]
},
searchMethod: {
type: Function,
default: () => {}
}
},
data() {
return {
pagination: null
}
},
methods: {
setCurrentPage(page) {
this.pagination.currentPage = page;
this.fetchData();
},
setPageSize(size) {
this.pagination.pageSize = size;
if (this.pagination.currentPage === 1) {
this.fetchData();
} else {
this.pagination.currentPage = 1;
}
},
fetchData() {
this.searchMethod(this.pagination, {
currentPage: this.pagination.currentPage,
pageSize: this.pagination.pageSize
});
},
mountPagination() {
const container = document.createElement('div');
const parent = this.$el.parentNode;
if (parent.lastChild == this.$el) {
parent.appentChild(container);
} else {
parent.insertBefore(container, this.$el.nextSibling);
}
const Pager = Vue.extend(Pagination);
this.pagination = new Pager({
components: { Pagination },
propsData: {
pageSize: this.pageSize,
pageSizes: this.pageSizes,
layout: this.pager_layout,
total: 0,
currentPage: 1
}
});
this.pagination.$on('current-change', this.setCurrentPage);
this.pagination.$on('size-change', this.setPageSize);
this.pagination.$mount(container);
}
},
mounted() {
if (this.showPagination) {
this.mountPagination();
}
},
beforeDestroy() {
this.pagination.$off('current-change', this.setCurrentPage);
this.pagination.$off('size-change', this.setPageSize);
}
}
使用:
<template>
<div>
<ex-table :data="data" show-pagination :search-method="handleSearch" ref="table">
<el-table-column label="column1" prop="prop1" />
</ex-table>
<el-button @click="$refs.table.setCurrentPage(1)">回到首頁(yè)</el-button>
</div>
</template>
<script>
import ExTable from './table.js';
export default {
components: { ExTable },
data() {
return {
data: []
}
},
methods: {
handleSearch(pagination, { currentPage, pageSize }) {
this.fetchRemoteData(currentPage, pageSize)
},
fetchRemoteData(currentPage, pageSize) {
//currentPage:當(dāng)前頁(yè), pageSize: 每頁(yè)最大條目數(shù)筷厘, 用于服務(wù)端分頁(yè)
//假設(shè)http請(qǐng)求數(shù)據(jù)挽铁,結(jié)果返回{data_list: [...], total: ..}
//設(shè)置表格數(shù)據(jù)
this.data = request.data_list;
//設(shè)置分頁(yè)總數(shù)
const pagination = this.$refs.table.pagination;
pagination .total = request.total;
},
},
mounted() {
this.$refs.table.fetchData();
}
}
</script>