vue 实现翻页
Vue 实现翻页功能
在 Vue 中实现翻页功能通常需要结合数据分页逻辑和前端交互设计。以下是常见的实现方法:
使用计算属性实现分页数据
通过计算属性动态计算当前页显示的数据:
data() {
return {
items: [], // 所有数据
currentPage: 1,
itemsPerPage: 10
}
},
computed: {
paginatedItems() {
const start = (this.currentPage - 1) * this.itemsPerPage
const end = start + this.itemsPerPage
return this.items.slice(start, end)
},
totalPages() {
return Math.ceil(this.items.length / this.itemsPerPage)
}
}
添加翻页控制方法
实现页面切换的控制器方法:

methods: {
goToPage(page) {
if (page >= 1 && page <= this.totalPages) {
this.currentPage = page
}
},
prevPage() {
if (this.currentPage > 1) {
this.currentPage--
}
},
nextPage() {
if (this.currentPage < this.totalPages) {
this.currentPage++
}
}
}
模板部分实现
在模板中添加分页导航控件:
<div v-for="item in paginatedItems" :key="item.id">
<!-- 显示分页后的数据 -->
</div>
<div class="pagination">
<button @click="prevPage" :disabled="currentPage === 1">上一页</button>
<span v-for="page in totalPages"
:key="page"
@click="goToPage(page)"
:class="{ active: currentPage === page }">
{{ page }}
</span>
<button @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
</div>
结合API实现后端分页
当数据量很大时,建议使用后端分页:

methods: {
async fetchData(page) {
const response = await axios.get('/api/items', {
params: {
page,
per_page: this.itemsPerPage
}
})
this.items = response.data.items
this.totalItems = response.data.total
}
}
使用第三方分页组件
可以集成成熟的UI库分页组件,如Element UI:
<el-pagination
@current-change="handleCurrentChange"
:current-page="currentPage"
:page-size="itemsPerPage"
:total="totalItems">
</el-pagination>
样式优化建议
为分页控件添加基本样式:
.pagination {
display: flex;
justify-content: center;
margin-top: 20px;
}
.pagination button, .pagination span {
margin: 0 5px;
cursor: pointer;
}
.pagination .active {
font-weight: bold;
color: #409EFF;
}
这些方法可以根据实际项目需求组合使用,前端分页适合数据量小的场景,后端分页适合大数据量情况。






