vue 实现分页功能
实现分页功能的方法
在Vue中实现分页功能可以通过多种方式完成,以下是一种常见的实现方法:
使用计算属性处理分页数据
通过计算属性对数据进行分页处理,结合分页组件实现交互:
<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 }} 页</span>
<button @click="nextPage" :disabled="currentPage === pageCount">下一页</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
currentPage: 1,
itemsPerPage: 10,
items: [] // 你的数据数组
}
},
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>
使用第三方分页组件
可以集成成熟的第三方分页组件,如Element UI的Pagination:
<template>
<div>
<el-table :data="paginatedData">
<el-table-column prop="name" label="名称"></el-table-column>
</el-table>
<el-pagination
@current-change="handleCurrentChange"
:current-page="currentPage"
:page-size="itemsPerPage"
:total="items.length"
layout="prev, pager, next">
</el-pagination>
</div>
</template>
<script>
export default {
data() {
return {
currentPage: 1,
itemsPerPage: 10,
items: [] // 你的数据数组
}
},
computed: {
paginatedData() {
const start = (this.currentPage - 1) * this.itemsPerPage
const end = start + this.itemsPerPage
return this.items.slice(start, end)
}
},
methods: {
handleCurrentChange(val) {
this.currentPage = val
}
}
}
</script>
服务器端分页实现
对于大数据量情况,建议实现服务器端分页:
<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="isLastPage">下一页</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
currentPage: 1,
itemsPerPage: 10,
items: [],
totalItems: 0
}
},
computed: {
isLastPage() {
return this.currentPage * this.itemsPerPage >= this.totalItems
}
},
methods: {
async fetchData(page) {
const response = await axios.get('/api/items', {
params: {
page,
size: this.itemsPerPage
}
})
this.items = response.data.items
this.totalItems = response.data.total
this.currentPage = page
}
},
created() {
this.fetchData(1)
}
}
</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 {
opacity: 0.5;
cursor: not-allowed;
}
以上方法可以根据项目需求选择适合的实现方式,客户端分页适合数据量小的场景,服务器端分页适合大数据量情况。







