App.vue
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
<script setup lang="ts"> import { ref, onMounted, computed } from "vue"; import axios from "axios"; import Paginate from "vuejs-paginate-next"; const posts = ref([]); // Store fetched posts const currentPage = ref(1); // Current page const itemsPerPage = 10; // Posts per page // Fetch data from JSONPlaceholder API const fetchPosts = async () => { try { const response = await axios.get("https://jsonplaceholder.typicode.com/posts"); posts.value = response.data; } catch (error) { console.error("Error fetching posts:", error); } }; // Get posts for the current page const paginatedPosts = computed(() => { const start = (currentPage.value - 1) * itemsPerPage; const end = start + itemsPerPage; return posts.value.slice(start, end); }); onMounted(fetchPosts); // Fetch posts on mount // Handle page change const handlePageChange = (pageNum: number) => { currentPage.value = pageNum; }; </script> <template> <div> <!-- Display the posts --> <ul> <li v-for="post in paginatedPosts" :key="post.id"> <h3>{{ post.title }}</h3> <p>{{ post.body }}</p> </li> </ul> <!-- Pagination component --> <paginate :page-count="Math.ceil(posts.length / itemsPerPage)" :click-handler="handlePageChange" :prev-text="'Prev'" :next-text="'Next'" :container-class="'pagination'" :page-class="'page-item'" /> </div> </template> <style> /* Adopt Bootstrap pagination styles */ @import "https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"; .pagination { display: flex; justify-content: center; gap: 5px; } .page-item { padding: 10px 15px; border: 1px solid #ddd; cursor: pointer; } .page-item:hover { background-color: #f0f0f0; } .active-page { background-color: #007bff; color: #fff; } </style> |