Vue 애플리케이션에서 페이지 매김을 구현하는 방법

Vue 애플리케이션에서 페이지 매김을 구현하는 방법

페이지 매김을 사용하면 대규모 데이터 세트를 더 작고 관리하기 쉬운 청크로 나눌 수 있습니다. 페이지 매김을 사용하면 사용자가 대규모 데이터 세트를 더 쉽게 탐색하고 원하는 정보를 찾을 수 있습니다.

Vue-Awesome-Paginate 시작하기

Vue-awesome-paginate는 페이지가 매겨진 데이터 표시를 만드는 프로세스를 단순화하는 강력하고 가벼운 Vue 페이지 매김 라이브러리입니다. 사용자 정의 가능한 구성 요소, 사용하기 쉬운 API 및 다양한 페이지 매김 시나리오 지원을 포함한 포괄적인 기능을 제공합니다.

vue-awesome-paginate 사용을 시작하려면 프로젝트 디렉터리에서 다음 터미널 명령을 실행하여 패키지를 설치하세요.

npm install vue-awesome-paginate

그런 다음 Vue 애플리케이션에서 작동하도록 패키지를 구성하려면 아래 코드를 src/main.js 파일에 복사하세요.

import { createApp } from "vue";import App from "./App.vue";import VueAwesomePaginate from "vue-awesome-paginate";import "vue-awesome-paginate/dist/style.css";createApp(App).use(VueAwesomePaginate).mount("#app");

이 코드는 .use() 메서드를 사용하여 패키지를 가져오고 등록하므로 애플리케이션의 어느 곳에서나 사용할 수 있습니다. 페이지 매김 패키지는 코드 블록도 가져오는 CSS 파일과 함께 제공됩니다.

테스트 Vue 애플리케이션 구축

vue-awesome-paginate 패키지의 작동 방식을 설명하기 위해 샘플 데이터 세트를 표시하는 Vue 앱을 빌드합니다. 이 앱에 대해 Axios를 사용하여 API에서 데이터를 가져 옵니다 .

아래 코드 블록을 App.vue 파일에 복사하세요.

<script setup>import { ref, onBeforeMount } from "vue";import axios from "axios";const comments = ref([]);const loadComments = async () => { try { const response = await axios.get( `https://jsonplaceholder.typicode.com/comments`, ); return response.data.map((comment) => comment.body); } catch (error) { console.error(error); }};onBeforeMount(async () => { const loadedComments = await loadComments(); comments.value.push(...loadedComments); console.log(comments.value);});</script><template> <div> <h1>Vue 3 Pagination with JSONPlaceholder</h1> <div v-if="comments.length"> <div v-for="comment in comments" class="comment"> <p>{{ comment }}</p> </div> </div> <div v-else> <p>Loading comments...</p> </div> </div></template>

이 코드 블록은 Vue Composition API를 사용하여 구성 요소를 빌드합니다. 구성 요소는 Vue가 마운트하기 전에 Axios를 사용하여 JSONPlaceholder API에서 주석을 가져옵니다( onBeforeMount 후크). 그런 다음 주석을 사용할 수 있을 때까지 템플릿을 사용하여 주석을 표시하거나 로딩 메시지를 사용하여 주석 배열에 주석을 저장합니다.

Vue-Awesome-Paginate를 Vue 앱에 통합하기

이제 API에서 데이터를 가져오는 간단한 Vue 앱이 있으므로 이를 수정하여 vue-awesome-paginate 패키지를 통합할 수 있습니다. 이 페이지 매김 기능을 사용하여 주석을 여러 페이지로 나눌 수 있습니다.

App.vue 파일 의 스크립트 섹션을 다음 코드로 바꿉니다 .

<script setup>import { ref, computed, onBeforeMount } from 'vue';import axios from 'axios';const perPage = ref(10);const currentPage = ref(1);const comments = ref([]);const onClickHandler = (page) => { console.log(page);};const loadComments = async () => { try { const response = await axios.get( `https://jsonplaceholder.typicode.com/comments` ); return response.data.map(comment => comment.body); } catch (error) { console.error(error); }};onBeforeMount(async () => { const loadedComments = await loadComments(); comments.value.push(...loadedComments); console.log(comments.value);});const displayedComments = computed(() => { const startIndex = (currentPage.value * perPage.value) - perPage.value; const endIndex = startIndex + perPage.value; return comments.value.slice(startIndex, endIndex);});</script>

이 코드 블록은 perPagecurrentPage 라는 두 개의 반응형 참조를 추가합니다 . 이러한 참조는 각각 페이지당 표시할 항목 수와 현재 페이지 번호를 저장합니다.

또한 이 코드는 displayComments 라는 이름의 계산된 참조를 생성합니다 . currentPageperPage 값을 기반으로 댓글 범위를 계산합니다 . 해당 범위 내의 주석 배열 조각을 반환하여 주석을 다른 페이지로 그룹화합니다.

이제 App.vue 파일의 템플릿 섹션을 다음으로 바꿉니다.

<template> <div> <h1>Vue 3 Pagination with JSONPlaceholder</h1> <div v-if="comments.length"> <div v-for="comment in displayedComments" class="comment"> <p>{{ comment }}</p> </div> <vue-awesome-paginate : total-items="comments.length" : items-per-page="perPage" : max-pages-shown="5" v-model="currentPage" : onclick="onClickHandler" /> </div> <div v-else> <p>Loading comments...</p> </div> </div></template>

이 템플릿 섹션의 목록을 렌더링하기 위한 v-for 속성은displayComments 배열을 가리킵니다. 템플릿은 위의 스니펫이 소품을 전달하는 vue-awesome-paginate 구성 요소를 추가합니다.

애플리케이션 스타일을 지정하면 다음과 같은 페이지가 표시됩니다.

페이지가 매겨진 댓글을 보여주는 Vue 앱의 사진.

번호가 매겨진 각 버튼을 클릭하면 다양한 댓글 세트가 표시됩니다.

더 나은 데이터 탐색을 위해 페이지 매김 또는 무한 스크롤 사용

이제 데이터를 효율적으로 페이지 매김하는 방법을 보여주는 매우 기본적인 Vue 앱이 생겼습니다. 또한 무한 스크롤을 사용하여 애플리케이션에서 긴 데이터 세트를 처리할 수도 있습니다. 페이지 매김과 무한 스크롤에는 장단점이 있으므로 선택하기 전에 앱의 요구 사항을 고려해야 합니다.

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다