element-ui 组件扩展 - 组合table 和 pagi
2017-11-04 本文已影响584人
RudolphWang
element-ui 中table 组件不带有分页,必须配合pagination组件来完成表格的分页功能,这对列表页面很多的系统来说,每次都需要定义分页组件相关的属性和事件,似乎做了很多重复的工作。下面通过写一个扩展组建来把table和pagination组件封装起来。
//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)">回到首页</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:当前页, pageSize: 每页最大条目数, 用于服务端分页
//假设http请求数据,结果返回{data_list: [...], total: ..}
//设置表格数据
this.data = request.data_list;
//设置分页总数
const pagination = this.$refs.table.pagination;
pagination .total = request.total;
},
},
mounted() {
this.$refs.table.fetchData();
}
}
</script>