vue翻页实现
Vue翻页实现方法
基础分页组件实现
使用v-for和计算属性实现基础分页逻辑:
<template>
<div>
<ul>
<li v-for="item in paginatedData" :key="item.id">{{ item.name }}</li>
</ul>
<button @click="prevPage" :disabled="currentPage === 1">上一页</button>
<span>第 {{ currentPage }} 页</span>
<button @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
</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)
}
},
methods: {
nextPage() {
this.currentPage++
},
prevPage() {
this.currentPage--
}
}
}
</script>
使用第三方库
对于复杂分页需求,可以使用专门的分页库:

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

methods: {
async fetchData(page = 1) {
const res = await axios.get(`/api/items?page=${page}&limit=10`)
this.items = res.data.items
this.totalPages = res.data.totalPages
}
}
分页样式优化
添加CSS美化分页控件:
.pagination {
display: flex;
list-style: none;
padding: 0;
}
.pagination li {
margin: 0 5px;
cursor: pointer;
}
.pagination li.active {
font-weight: bold;
}
动态分页大小
允许用户选择每页显示数量:
<select v-model="itemsPerPage" @change="resetPagination">
<option value="5">5条/页</option>
<option value="10">10条/页</option>
<option value="20">20条/页</option>
</select>
methods: {
resetPagination() {
this.currentPage = 1
}
}






