用vue实现分页
使用 Vue 实现分页功能
基础分页组件实现
创建分页组件 Pagination.vue,包含页码按钮、上一页和下一页按钮:
<template>
<div class="pagination">
<button @click="prevPage" :disabled="currentPage === 1">上一页</button>
<button
v-for="page in pages"
:key="page"
@click="changePage(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
},
currentPage: {
type: Number,
default: 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: {
changePage(page) {
this.$emit('page-changed', page);
},
prevPage() {
if (this.currentPage > 1) {
this.$emit('page-changed', this.currentPage - 1);
}
},
nextPage() {
if (this.currentPage < this.totalPages) {
this.$emit('page-changed', this.currentPage + 1);
}
}
}
};
</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="itemsPerPage"
:current-page="currentPage"
@page-changed="handlePageChange"
/>
</div>
</template>
<script>
import Pagination from './Pagination.vue';
export default {
components: {
Pagination
},
data() {
return {
currentPage: 1,
itemsPerPage: 5,
items: [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
// 更多数据...
]
};
},
computed: {
paginatedItems() {
const start = (this.currentPage - 1) * this.itemsPerPage;
const end = start + this.itemsPerPage;
return this.items.slice(start, end);
}
},
methods: {
handlePageChange(page) {
this.currentPage = page;
}
}
};
</script>
高级分页优化
对于大量数据时,可以优化分页显示,只显示当前页附近的页码:

// 在Pagination.vue的computed中替换pages计算属性
pages() {
const range = [];
const visiblePages = 5; // 显示5个页码
let start = Math.max(1, this.currentPage - Math.floor(visiblePages / 2));
let end = Math.min(this.totalPages, start + visiblePages - 1);
if (end - start + 1 < visiblePages) {
start = Math.max(1, end - visiblePages + 1);
}
for (let i = start; i <= end; i++) {
range.push(i);
}
return range;
}
服务器端分页
当数据量很大时,应该实现服务器端分页:
methods: {
async fetchData(page) {
const response = await axios.get(`/api/items?page=${page}&limit=${this.itemsPerPage}`);
this.items = response.data.items;
this.totalItems = response.data.total;
},
handlePageChange(page) {
this.currentPage = page;
this.fetchData(page);
}
}
分页样式优化
可以使用流行的UI框架如Element UI或Vuetify的内置分页组件:
<template>
<el-pagination
@current-change="handlePageChange"
:current-page="currentPage"
:page-size="itemsPerPage"
:total="totalItems"
layout="prev, pager, next">
</el-pagination>
</template>
以上实现涵盖了从基础到高级的Vue分页功能,可以根据项目需求选择适合的方案。






