vue 分页的实现
Vue 分页的实现方法
基础分页实现
使用v-for渲染分页按钮,结合计算属性动态计算分页数据:
<template>
<div>
<ul>
<li v-for="item in paginatedData" :key="item.id">{{ item.name }}</li>
</ul>
<div class="pagination">
<button
v-for="page in totalPages"
:key="page"
@click="currentPage = page"
:class="{ active: currentPage === page }"
>
{{ page }}
</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [], // 原始数据
currentPage: 1,
itemsPerPage: 10
}
},
computed: {
totalPages() {
return Math.ceil(this.items.length / this.itemsPerPage)
},
paginatedData() {
const start = (this.currentPage - 1) * this.itemsPerPage
const end = start + this.itemsPerPage
return this.items.slice(start, end)
}
}
}
</script>
使用第三方库
对于更复杂的分页需求,可以使用vuejs-paginate等专门的分页组件:
安装库:

npm install vuejs-paginate
使用示例:
<template>
<div>
<paginate
:page-count="totalPages"
:click-handler="changePage"
:prev-text="'<'"
:next-text="'>'"
:container-class="'pagination'"
/>
</div>
</template>
<script>
import Paginate from 'vuejs-paginate'
export default {
components: {
Paginate
},
methods: {
changePage(pageNum) {
this.currentPage = pageNum
}
}
}
</script>
服务器端分页
当数据量很大时,建议使用服务器端分页:

methods: {
async fetchData(page = 1) {
const response = await axios.get(`/api/items?page=${page}`)
this.items = response.data.items
this.totalPages = response.data.totalPages
}
}
分页样式优化
添加CSS样式增强用户体验:
.pagination {
display: flex;
list-style: none;
padding: 0;
}
.pagination button {
margin: 0 5px;
padding: 5px 10px;
border: 1px solid #ddd;
cursor: pointer;
}
.pagination button.active {
background-color: #4CAF50;
color: white;
border: 1px solid #4CAF50;
}
分页功能扩展
实现更丰富的分页功能,如每页条数选择器:
<template>
<div>
<select v-model="itemsPerPage" @change="resetPage">
<option value="5">5条/页</option>
<option value="10">10条/页</option>
<option value="20">20条/页</option>
</select>
</div>
</template>
<script>
export default {
methods: {
resetPage() {
this.currentPage = 1
}
}
}
</script>






