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 }} / {{ totalPages }}</span>
<button @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
// ...更多数据
],
currentPage: 1,
itemsPerPage: 5
}
},
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() {
if (this.currentPage < this.totalPages) {
this.currentPage++
}
},
prevPage() {
if (this.currentPage > 1) {
this.currentPage--
}
}
}
}
</script>
使用第三方分页组件
Element UI 的分页组件示例:

<template>
<div>
<el-table :data="paginatedData">
<!-- 表格列定义 -->
</el-table>
<el-pagination
@current-change="handleCurrentChange"
:current-page="currentPage"
:page-size="itemsPerPage"
:total="totalItems"
layout="prev, pager, next">
</el-pagination>
</div>
</template>
<script>
export default {
data() {
return {
currentPage: 1,
itemsPerPage: 10,
totalItems: 100,
allData: [] // 假设已加载全部数据
}
},
computed: {
paginatedData() {
const start = (this.currentPage - 1) * this.itemsPerPage
const end = start + this.itemsPerPage
return this.allData.slice(start, end)
}
},
methods: {
handleCurrentChange(val) {
this.currentPage = val
}
}
}
</script>
后端分页实现
通过 API 请求实现分页:

methods: {
fetchData(page = 1) {
axios.get(`/api/items?page=${page}&per_page=${this.itemsPerPage}`)
.then(response => {
this.paginatedData = response.data.items
this.totalItems = response.data.total
})
},
handlePageChange(page) {
this.fetchData(page)
}
}
分页样式优化
添加基础 CSS 样式:
.pagination {
display: flex;
justify-content: center;
margin-top: 20px;
}
.pagination button {
margin: 0 5px;
padding: 5px 10px;
}
.pagination span {
line-height: 30px;
margin: 0 10px;
}
关键点:
- 计算属性处理数据切片
- 分页按钮事件绑定
- 考虑总页数和禁用状态
- 支持前端或后端分页模式






