Vue.jsを使えば、大量のリストデータをページ単位で表示する「ページネーション機能」も簡単に実装できます。本記事では、1ページあたりの表示件数を制御し、前後のページ切り替えができるシンプルなページネーション付きリストの作成方法を紹介します。
ページネーション機能とは?
ページネーションとは、表示するリストが多すぎる場合に、複数のページに分割して表示する仕組みです。Vue.jsでは、現在のページ番号と表示件数をもとにcomputed
で表示リストを制御することで、柔軟なページネーションUIが実現できます。
基本的な実装例
以下は、Vue 3のComposition APIで実装したシンプルなページネーション付きリストの例です。前へ/次へボタンと、ページ番号によるナビゲーションを実装しています。
<template>
<div class="pagination-container">
<ul class="item-list">
<li v-for="(item, index) in paginatedItems" :key="index">
{{ item }}
</li>
</ul>
<div class="pagination-controls">
<button @click="goToPage(currentPage - 1)" :disabled="currentPage === 1">前へ</button>
<button
v-for="page in totalPages"
:key="page"
@click="goToPage(page)"
:class="{ active: page === currentPage }"
>
{{ page }}
</button>
<button @click="goToPage(currentPage + 1)" :disabled="currentPage === totalPages">次へ</button>
</div>
</div>
</template>
<script setup>
import { ref, computed } from 'vue';
const allItems = ref([
'項目1', '項目2', '項目3', '項目4', '項目5',
'項目6', '項目7', '項目8', '項目9', '項目10',
'項目11', '項目12', '項目13', '項目14', '項目15'
]);
const itemsPerPage = 5;
const currentPage = ref(1);
const totalPages = computed(() => {
return Math.ceil(allItems.value.length / itemsPerPage);
});
const paginatedItems = computed(() => {
const start = (currentPage.value - 1) * itemsPerPage;
return allItems.value.slice(start, start + itemsPerPage);
});
const goToPage = (page) => {
if (page >= 1 && page <= totalPages.value) {
currentPage.value = page;
}
};
</script>
<style scoped>
.pagination-container {
max-width: 500px;
margin: 2rem auto;
text-align: center;
}
.item-list {
list-style: none;
padding: 0;
}
.item-list li {
padding: 0.5rem 0;
border-bottom: 1px solid #ddd;
}
.pagination-controls {
margin-top: 1rem;
}
.pagination-controls button {
margin: 0 0.25rem;
padding: 0.4rem 0.8rem;
cursor: pointer;
}
.pagination-controls button.active {
background-color: #007acc;
color: #fff;
}
.pagination-controls button:disabled {
background-color: #ccc;
cursor: not-allowed;
}
</style>
実装のポイント
- currentPage: 現在のページ番号をrefで管理
- computed: 全件数からページ数を算出、表示対象を抽出
- ページ移動関数: 範囲外を制限し、クリックで現在ページを更新
ページ数の計算にはMath.ceil()
を使い、切り捨てを防いでいます。また、ページ数が少ない場合でもボタンが正しく表示されるように制御しています。
拡張のアイデア
- ページサイズ(1ページあたりの件数)の切り替え機能
- 現在のページをURLに反映し、リロードしても状態を維持
- 非同期APIによるデータ取得と連携した動的ページネーション
まとめ
Vue.jsでは、状態管理とcomputedの組み合わせでページネーション機能も簡単に実装できます。大量のリストを扱う場面では、ユーザーがスムーズに閲覧できるようにページ分割することで、UXの向上が期待できます。シンプルな構成から始め、必要に応じて拡張していきましょう。