简易分页组件
<script setup name="Pagination">
const props = defineProps({
totalItems: { type: Number, default: 0 },
pageSize: { type: Number, default: 10 },
});
const { totalItems, pageSize } = toRefs(props);
const currentPage = ref(1);
const totalPages = computed(() => {
return Math.ceil(totalItems.value / pageSize.value);
});
const emits = defineEmits(["page-change"]);
const prevPage = () => {
if (currentPage.value > 1) {
currentPage.value--;
emits("page-change", currentPage.value);
}
};
const nextPage = () => {
if (currentPage.value < totalPages.value) {
currentPage.value++;
emits("page-change", currentPage.value);
}
};
const gotoFirstPage = () => {
currentPage.value = 1;
emits("page-change", currentPage.value);
};
const gotoLastPage = () => {
currentPage.value = totalPages.value;
emits("page-change", currentPage.value);
};
</script>
<template>
<div class="pagination">
<button @click="gotoFirstPage" :disabled="currentPage === 1">首页</button>
<button @click="prevPage" :disabled="currentPage === 1">上一页</button>
<span>{{ currentPage }}/{{ totalPages }}</span>
<button
@click="nextPage"
:disabled="currentPage === totalPages || totalPages === 0"
>
下一页
</button>
<button
@click="gotoLastPage"
:disabled="currentPage === totalPages || totalPages === 0"
>
尾页
</button>
</div>
</template>
<style scoped>
.pagination span,
.pagination button {
margin: 0 10px 0 0;
}
</style>
调用组件
<script setup>
import Pagination from "./Pagination.vue";
const pageChange = (currentPage) => {
alert(currentPage);
};
</script>
<template>
<pagination
:total-items="1000"
:page-size="20"
@pageChange="pageChange"
></pagination>
</template>