vue实现简单分页器
Vue 实现简单分页器的方法
基础分页器组件
创建一个基础的 Pagination 组件,包含页码按钮和导航逻辑:
<template>
<div class="pagination">
<button
@click="prevPage"
:disabled="currentPage === 1"
>上一页</button>
<button
v-for="page in pages"
:key="page"
@click="goToPage(page)"
:class="{ active: currentPage === page }"
>{{ page }}</button>
<button
@click="nextPage"
:disabled="currentPage === totalPages"
>下一页</button>
</div>
</template>
<script>
export default {
props: {
totalItems: { type: Number, required: true },
itemsPerPage: { type: Number, default: 10 }
},
data() {
return { currentPage: 1 }
},
computed: {
totalPages() {
return Math.ceil(this.totalItems / this.itemsPerPage)
},
pages() {
const range = []
for (let i = 1; i <= this.totalPages; i++) {
range.push(i)
}
return range
}
},
methods: {
prevPage() {
if (this.currentPage > 1) this.currentPage--
},
nextPage() {
if (this.currentPage < this.totalPages) this.currentPage++
},
goToPage(page) {
this.currentPage = page
}
}
}
</script>
<style>
.pagination button {
margin: 0 5px;
padding: 5px 10px;
}
.pagination button.active {
background-color: #42b983;
color: white;
}
</style>
使用分页器组件
在父组件中使用分页器并绑定数据:
<template>
<div>
<!-- 显示当前页数据 -->
<ul>
<li v-for="item in paginatedItems" :key="item.id">
{{ item.name }}
</li>
</ul>
<!-- 分页器 -->
<Pagination
:total-items="items.length"
:items-per-page="perPage"
@page-change="handlePageChange"
/>
</div>
</template>
<script>
import Pagination from './Pagination.vue'
export default {
components: { Pagination },
data() {
return {
items: [], // 从API获取的数据
perPage: 5,
currentPage: 1
}
},
computed: {
paginatedItems() {
const start = (this.currentPage - 1) * this.perPage
const end = start + this.perPage
return this.items.slice(start, end)
}
},
methods: {
handlePageChange(page) {
this.currentPage = page
}
}
}
</script>
高级分页功能(可选)
实现更复杂的分页逻辑,如显示有限页码:
// 在Pagination组件的computed中替换pages计算属性
pages() {
const range = []
const maxVisible = 5 // 最多显示5个页码
let start = 1
if (this.totalPages > maxVisible) {
start = Math.min(
Math.max(1, this.currentPage - Math.floor(maxVisible / 2)),
this.totalPages - maxVisible + 1
)
}
const end = Math.min(start + maxVisible - 1, this.totalPages)
for (let i = start; i <= end; i++) {
range.push(i)
}
return range
}
与API集成
当需要从后端获取分页数据时:
methods: {
async fetchData(page = 1) {
const response = await axios.get(`/api/items?page=${page}`)
this.items = response.data.items
this.totalItems = response.data.total
},
handlePageChange(page) {
this.currentPage = page
this.fetchData(page)
}
}
响应式设计优化
添加响应式样式适应不同设备:
@media (max-width: 600px) {
.pagination button {
padding: 3px 6px;
margin: 0 2px;
min-width: 30px;
}
}
实现一个完整的分页器需要考虑当前页码状态管理、页面跳转逻辑、样式交互以及与实际数据的绑定。以上方案提供了从基础到进阶的实现方式,可根据具体需求进行调整。







