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">Previous</button>
<span>{{ currentPage }} / {{ totalPages }}</span>
<button @click="nextPage" :disabled="currentPage === totalPages">Next</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)
}
},
methods: {
nextPage() {
if (this.currentPage < this.totalPages) {
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">Previous</button>
<span>{{ currentPage }} / {{ totalPages }}</span>
<button @click="fetchData(currentPage + 1)" :disabled="currentPage === totalPages">Next</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [],
currentPage: 1,
itemsPerPage: 10,
totalPages: 1
}
},
mounted() {
this.fetchData(1)
},
methods: {
async fetchData(page) {
try {
const response = await axios.get('/api/items', {
params: {
page,
limit: this.itemsPerPage
}
})
this.items = response.data.items
this.totalPages = response.data.totalPages
this.currentPage = page
} catch (error) {
console.error(error)
}
}
}
}
</script>
使用分页组件库
可以使用现成的分页组件如Element UI的Pagination:
<template>
<div>
<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 {
currentPage: 1,
pageSize: 10,
total: 100
}
},
methods: {
handleCurrentChange(val) {
this.currentPage = val
this.fetchData()
},
fetchData() {
// 获取数据逻辑
}
}
}
</script>
分页样式优化
可以为分页控件添加CSS样式增强用户体验:
.pagination {
margin-top: 20px;
display: flex;
justify-content: center;
align-items: center;
gap: 10px;
}
.pagination button {
padding: 5px 10px;
cursor: pointer;
}
.pagination button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
这些方法可以根据具体需求选择或组合使用,前端分页适合小数据量,后端分页适合大数据量,组件库则提供了快速实现的方案。







