分页实现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">Previous</button>
<span>Page {{ currentPage }} of {{ totalPages }}</span>
<button @click="nextPage" :disabled="currentPage === totalPages">Next</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
currentPage: 1,
itemsPerPage: 10,
allItems: [] // 假设这是从API获取的所有数据
}
},
computed: {
totalPages() {
return Math.ceil(this.allItems.length / this.itemsPerPage)
},
paginatedData() {
const start = (this.currentPage - 1) * this.itemsPerPage
const end = start + this.itemsPerPage
return this.allItems.slice(start, end)
}
},
methods: {
nextPage() {
if (this.currentPage < this.totalPages) {
this.currentPage++
}
},
prevPage() {
if (this.currentPage > 1) {
this.currentPage--
}
}
}
}
</script>
后端分页实现
适用于大数据量场景,每次只请求当前页的数据。
<template>
<div>
<table>
<tr v-for="item in items" :key="item.id">
<td>{{ item.name }}</td>
</tr>
</table>
<div class="pagination">
<button @click="fetchPage(currentPage - 1)" :disabled="currentPage === 1">Previous</button>
<span>Page {{ currentPage }} of {{ totalPages }}</span>
<button @click="fetchPage(currentPage + 1)" :disabled="currentPage === totalPages">Next</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
currentPage: 1,
itemsPerPage: 10,
items: [],
totalItems: 0
}
},
computed: {
totalPages() {
return Math.ceil(this.totalItems / this.itemsPerPage)
}
},
methods: {
async fetchPage(page) {
if (page < 1 || page > this.totalPages) return
const response = await axios.get('/api/items', {
params: {
page,
limit: this.itemsPerPage
}
})
this.items = response.data.items
this.totalItems = response.data.total
this.currentPage = page
}
},
created() {
this.fetchPage(1)
}
}
</script>
使用第三方组件
对于更复杂的分页需求,可以使用现成的分页组件:
-
安装Element UI分页组件:
npm install element-ui -
使用示例:
<template> <div> <el-pagination @current-change="handleCurrentChange" :current-page="currentPage" :page-size="pageSize" :total="total" layout="prev, pager, next"> </el-pagination> </div> </template>
export default { components: { ElPagination }, data() { return { currentPage: 1, pageSize: 10, total: 100 } }, methods: { handleCurrentChange(val) { this.currentPage = val this.fetchData() }, fetchData() { // 获取新页面的数据 } } }
```分页样式优化
可以添加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;
}
以上方法可根据具体项目需求选择或组合使用,后端分页更适合大数据量场景,前端分页则适合小数据集快速实现。







