vue实现网页分页
Vue实现网页分页的方法
在Vue中实现网页分页通常需要结合前端数据分页和后端API分页。以下是两种常见的实现方式:
前端数据分页
适用于数据量较小的情况,数据一次性加载后在前端进行分页处理。
<template>
<div>
<table>
<tr v-for="item in paginatedData" :key="item.id">
<td>{{ item.name }}</td>
</tr>
</table>
<div class="pagination">
<button @click="prevPage" :disabled="currentPage === 1">上一页</button>
<span>第 {{ currentPage }} 页 / 共 {{ pageCount }} 页</span>
<button @click="nextPage" :disabled="currentPage === pageCount">下一页</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [], // 所有数据
currentPage: 1,
itemsPerPage: 10
}
},
computed: {
pageCount() {
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.pageCount) {
this.currentPage++
}
},
prevPage() {
if (this.currentPage > 1) {
this.currentPage--
}
}
}
}
</script>
后端API分页
适用于数据量大的情况,每次请求只获取当前页的数据。
<template>
<div>
<table>
<tr v-for="item in items" :key="item.id">
<td>{{ item.name }}</td>
</tr>
</table>
<div class="pagination">
<button @click="fetchData(currentPage - 1)" :disabled="currentPage === 1">上一页</button>
<span>第 {{ currentPage }} 页</span>
<button @click="fetchData(currentPage + 1)" :disabled="!hasNext">下一页</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [],
currentPage: 1,
hasNext: false
}
},
methods: {
async fetchData(page) {
try {
const response = await axios.get(`/api/items?page=${page}&size=10`)
this.items = response.data.items
this.hasNext = response.data.hasNext
this.currentPage = page
} catch (error) {
console.error(error)
}
}
},
created() {
this.fetchData(1)
}
}
</script>
使用分页组件库
可以使用现成的Vue分页组件,如Element UI的Pagination:
<template>
<div>
<el-table :data="tableData">
<el-table-column prop="name" label="名称"></el-table-column>
</el-table>
<el-pagination
@current-change="handleCurrentChange"
:current-page="currentPage"
:page-size="pageSize"
:total="total"
layout="prev, pager, next">
</el-pagination>
</div>
</template>
<script>
export default {
data() {
return {
tableData: [],
currentPage: 1,
pageSize: 10,
total: 0
}
},
methods: {
handleCurrentChange(val) {
this.currentPage = val
this.fetchData()
},
async fetchData() {
const response = await axios.get(`/api/items?page=${this.currentPage}&size=${this.pageSize}`)
this.tableData = response.data.items
this.total = response.data.total
}
},
created() {
this.fetchData()
}
}
</script>
分页样式优化
可以为分页按钮添加CSS样式,提升用户体验:
.pagination {
margin-top: 20px;
display: flex;
justify-content: center;
align-items: center;
gap: 10px;
}
.pagination button {
padding: 5px 10px;
border: 1px solid #ddd;
background: #fff;
cursor: pointer;
}
.pagination button:disabled {
color: #ccc;
cursor: not-allowed;
}
以上方法可以根据实际项目需求选择适合的实现方式,前端分页适合数据量小的场景,后端分页适合大数据量情况,组件库可以快速实现标准化分页功能。







