首页、上一页、下一页、末页、跳转按钮
- 因为el-pagination只有一个插槽,所以通过两个el-pagination插槽分别加入首页、末页按钮,再拼接这两个el-pagination的方式来实现首页、末页按钮
- 跳转按钮不用加事件,如果el-pagination修改了前往的页数,失焦时会触发current-change事件,造成了一种似乎是点击按钮跳转的效果(实际上点击其他地方失焦也会触发current-change事件)
html
<template>
<div class="pagination">
<el-pagination
prev-text="上一页"
next-text="下一页"
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
:current-page="tableParams.pageNum"
:page-sizes="[20, 30, 40]"
:page-size="tableParams.pageSize"
layout="total, sizes, slot, prev, pager, next"
:total="tableParams.total">
<button
type="button"
class="btn-prev"
@click="jumpFirstPage"
:disabled="isFirstPage">
<span>首页</span>
</button>
</el-pagination>
<el-pagination
prev-text="上一页"
next-text="下一页"
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
:current-page="tableParams.pageNum"
:page-sizes="[20, 30, 40]"
:page-size="tableParams.pageSize"
layout="slot, jumper"
:total="tableParams.total">
<button
type="button"
class="btn-prev"
@click="jumpLastPage"
:disabled="isLastPage">
<span>末页</span>
</button>
</el-pagination>
<el-button
type="primary"
size="mini"
class="ml">
前往
</el-button>
</div>
</template>
<script>
export default {
props: {
tableParams: {
type: Object,
},
},
computed: {
isFirstPage() {
// 如果只有1页,禁用首页
return this.tableParams.pageNum === 1;
},
isLastPage() {
return (
// 如果只有1页,禁用末页,或者已经处于末页,禁用
Math.ceil(this.tableParams.total / this.tableParams.pageSize) === 0 ||
this.tableParams.pageNum ===
Math.ceil(this.tableParams.total / this.tableParams.pageSize)
);
},
},
methods: {
handleSizeChange(val) {
this.$emit('size-change', val);
},
handleCurrentChange(val) {
this.$emit('current-change', val);
},
jumpFirstPage() {
this.handleCurrentChange(1);
},
jumpLastPage() {
this.handleCurrentChange(
Math.ceil(this.tableParams.total / this.tableParams.pageSize)
);
},
},
};
</script>
<style lang="scss" scoped>
.pagination {
padding: 6px;
border: 1px solid #c0eae7;
border-top: 0px;
display: flex;
justify-content: flex-end;
align-items: center;
border-radius: 4px;
border-top-left-radius: 0px;
border-top-right-radius: 0px;
}
:deep(.el-button--mini) {
padding: 5px 15px;
height: 24.22px;
margin-left: 10px;
}
</style>
使用
html
<Pagination
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
:tableParams="tableParams"></Pagination>
组件默认pageNum 从1开始,如果接口是从0开始,传参时-1即可
js
tableParams: {
pageNum: 1,
pageSize: 30,
total: 0,
},
js
handleSizeChange(val) {
// 条数变更后如果pageNum不变可能会导致查询为空,所以还原为1
this.tableParams.pageNum = 1;
this.tableParams.pageSize = val;
this.getTableData();
},
handleCurrentChange(val) {
this.tableParams.pageNum = val;
this.getTableData();
},
js
async getTableData() {
this.tableData = [];
this.tableLoading++;
const { data: res } = await http({
method: 'get',
url: '/show/listData',
data: {},
params: {
pageIndex: this.tableParams.pageNum,
pageSize: this.tableParams.pageSize,
},
});
if (res.code === 0) {
this.tableData = res.data;
this.tableParams.total = res.total;
}
this.tableLoading--;
},