61 lines
1.4 KiB
JavaScript

import { computed, ref } from 'vue';
export function usePagination(initialConfig) {
const currentPage = ref(initialConfig.currentPage);
const pageSize = ref(initialConfig.pageSize);
const totalItems = ref(initialConfig.totalItems);
const totalPages = computed(() => Math.ceil(totalItems.value / pageSize.value));
const startIndex = computed(() => (currentPage.value - 1) * pageSize.value);
const endIndex = computed(() => Math.min(startIndex.value + pageSize.value, totalItems.value));
const hasNextPage = computed(() => currentPage.value < totalPages.value);
const hasPreviousPage = computed(() => currentPage.value > 1);
const goToPage = (page) => {
if (page >= 1 && page <= totalPages.value) {
currentPage.value = page;
}
};
const nextPage = () => {
if (hasNextPage.value) {
currentPage.value++;
}
};
const previousPage = () => {
if (hasPreviousPage.value) {
currentPage.value--;
}
};
const setPageSize = (size) => {
pageSize.value = size;
currentPage.value = 1;
};
const updateTotalItems = (total) => {
totalItems.value = total;
};
return {
currentPage,
pageSize,
totalItems,
totalPages,
startIndex,
endIndex,
hasNextPage,
hasPreviousPage,
goToPage,
nextPage,
previousPage,
setPageSize,
updateTotalItems,
};
}