JAVASCRIPT
Building a Reusable Pagination Composable in Vue 3
Create a flexible and reusable pagination logic using a Vue 3 Composition API composable to manage large lists of items efficiently within your components.
// composables/usePagination.js
import { ref, computed } from 'vue';
export function usePagination(items, itemsPerPage = 10) {
const currentPage = ref(1);
const totalPages = computed(() => {
return Math.ceil(items.value.length / itemsPerPage);
});
const paginatedItems = computed(() => {
const start = (currentPage.value - 1) * itemsPerPage;
const end = start + itemsPerPage;
return items.value.slice(start, end);
});
function goToPage(page) {
if (page >= 1 && page <= totalPages.value) {
currentPage.value = page;
}
}
function nextPage() {
goToPage(currentPage.value + 1);
}
function prevPage() {
goToPage(currentPage.value - 1);
}
return {
currentPage,
totalPages,
paginatedItems,
goToPage,
nextPage,
prevPage,
};
}
// MyComponent.vue
<template>
<div>
<ul>
<li v-for="item in paginatedItems" :key="item.id">{{ item.name }}</li>
</ul>
<button @click="prevPage" :disabled="currentPage === 1">Previous</button>
<span>Page {{ currentPage }} of {{ totalPages }}</span>
<button @click="nextPage" :disabled="currentPage === totalPages">Next</button>
<button v-for="page in totalPages" :key="page" @click="goToPage(page)" :class="{ 'active': currentPage === page }">
{{ page }}
</button>
</div>
</template>
<script setup>
import { ref } from 'vue';
import { usePagination } from './composables/usePagination';
const allItems = ref(
Array.from({ length: 100 }, (_, i) => ({ id: i + 1, name: `Item ${i + 1}` }))
);
const { currentPage, totalPages, paginatedItems, goToPage, nextPage, prevPage } = usePagination(allItems, 10);
</script>
How it works: This snippet shows how to create a flexible `usePagination` composable in Vue 3, leveraging the Composition API for reusable logic. It manages current page, calculates total pages, and computes the slice of items for the current page. The example component demonstrates how to integrate this composable to display paginated data and navigate between pages, enabling easy list management without direct API interaction.