代码有未尽之处,欢迎大家评论,友善交流。
前提:参考element-plus分页组件Pagination
- 子组件Pagination.vue:
<template>
<div class="pagination-container">
<el-pagination :background="background"
v-model:currentPage="currentPage"
v-model:pageSize="pageSize"
:layout="layout"
:pager-count="pagerCount"
:total="total"
:page-sizes="pageSizes" />
</div>
</template>
<script setup lang="ts">
import { defineProps, defineEmits, computed } from "vue";
const emits = defineEmits(["update:page", "update:size"]);
const currentPage = computed({
get() {
return props.page;
},
set(val) {
emits("update:page", val);
},
});
const pageSize = computed({
get() {
return props.size;
},
set(val) {
emits("update:size", val);
},
});
const props = defineProps({
page: {
type: Number,
default: 1,
},
size: {
type: Number,
default: 10,
},
background: {
type: Boolean,
default: false,
},
layout: {
type: String,
default: "total, sizes, prev, pager, next, jumper",
},
//设置最大页码按钮数。 页码按钮的数量,当总页数超过该值时会折叠
pagerCount: {
type: Number,
default: 7,
},
total: {
type: Number,
required: true,
},
pageSizes: {
type: Array,
default: () => [10, 20, 30, 50],
},
});
</script>
<style lang="scss" scoped>
.pagination-container {
display: flex;
justify-content: flex-end;
margin: 15px 0;
background-color: #ffffff;
}
</style>
- 父组件使用:
// 先import
<Pagination v-model:page="query.pageNumber"
v-model:size="query.pageSize"
:total="total"
@update:page="handlePageChange"
@update:size="handleSizeChange" />
<script setup lang="ts">
import { ref } from 'vue';
const total = ref(0);
const query = ref({
pageNumber: 1,
pageSize: 10
});
// 换页,重新获取表格
const handlePageChange = (val) => {
query.value.pageNumber = val;
getTableData();
};
const handleSizeChange = (val) => {
query.value.pageSize = val;
getTableData();
};
</script>