分页组件封装
对于我们前端来说,分页功能是必不可少的。
几乎每个页面都有它的存在,为了减少代码的冗余量,对于这些经常用到的功能呢,我们就会把它写成组件封装起来。
今天我们就来实现分页功能的封装。
<template>
<div class="my-pagination" :style="{ textAlign: textAlign }">
<el-pagination
:current-page="page.current"
:page-size="page.size"
:total="page.total"
:pager-count="pagerCount"
:layout="layout"
background
v-bind="$attrs"
v-on="$listeners"
/>
</div>
</template>
<script>
export default {
name: "MyPagination",
props: {
page: {
type: Object,
required: true,
},
layout: {
type: String,
default: "total, prev, pager, next, jumper",
},
textAlign: {
type: String,
default: "right",
},
pagerCount: {
type: Number,
default: 5,
},
},
};
</script>
<style scoped>
.my-pagination {
margin: 20px 0;
}
</style>
组件封装好了以后呢,我们就去页面上进行引用
//html
<template>
<Pagination
:page="page"
@current-change="handleCurrentPage"
@handlePageSize="handlePageSize"
/>
</template>
引入组件
import Pagination from "@/components/Pagination";
// 默认分页
const pageDefault = { current: 1, size: 10, total: 0 };
export default {
components: { Pagination },
data() {
return {
tableData: [],
//分页
// 搜索相关
search: { ...searchDefault },
page: { ...pageDefault },
},
}
computed: {
// 合并查询参数
mergeParams() {
return {
...this.search,
current: this.page.current,
size: this.page.size,
};
},
},
created() {
this.getTableData();
},
method:{
// 获取公告分页数据
getTableData() {
this.loading = true;
axios
.post("/xx/xx/page", this.mergeParams)
.then((value) => {
this.tableData = value.data.data.records || [];
this.page.total = value.data.data.total;
})
.finally(() => {
this.loading = false;
});
},
// 点击搜索
handleClickSearch() {
this.page.current = 1;
this.tableData = [];
this.page.total = 0;
this.getTableData(true);
},
// 点击重置搜索
handleRestSearch() {
this.search = { ...searchDefault };
this.page = { ...pageDefault };
this.getTableData();
},
// 分页相关 改变current
handleCurrentPage(val) {
this.page.current = val;
this.getTableData();
},
// 分页相关 改变size
handlePageSize(val) {
this.page.size = val;
this.getTableData();
},
}
以上默认搜索和分页使用同一个接口