vue 3 simple pagination composable in typescript

index.ts
import { ref, computed, ComputedRef } from 'vue';

interface Pagination {
  currentPage: ComputedRef<number>,
  goToPage: (page: number) => void,
  goToNextPage: () => void,
  goToPrevPage: () => void,
}

export function usePagination(totalItems: number, itemsPerPage: number): Pagination {
  const currentPage = ref(1);

  const maxPages = Math.ceil(totalItems / itemsPerPage);

  function goToPage(page: number) {
    if (page >= 1 && page <= maxPages) {
      currentPage.value = page;
    }
  }

  function goToNextPage() {
    if (currentPage.value < maxPages) {
      currentPage.value++;
    }
  }

  function goToPrevPage() {
    if (currentPage.value > 1) {
      currentPage.value--;
    }
  }

  return {
    currentPage: computed(() => currentPage.value),
    goToPage,
    goToNextPage,
    goToPrevPage,
  };
}
825 chars
40 lines

related categories

gistlibby LogSnag