分页用vue实现
分页用 Vue 实现
在 Vue 中实现分页功能通常需要结合数据管理和 UI 组件。以下是几种常见的方法:
使用 Vue 组件库的分页组件
许多 Vue UI 组件库(如 Element UI、Vant、Ant Design Vue)提供了现成的分页组件。以 Element UI 为例:
<template>
<el-pagination
:current-page="currentPage"
:page-size="pageSize"
:total="total"
@current-change="handleCurrentChange"
/>
</template>
<script>
export default {
data() {
return {
currentPage: 1,
pageSize: 10,
total: 100
}
},
methods: {
handleCurrentChange(val) {
this.currentPage = val
this.fetchData()
},
fetchData() {
// 根据 currentPage 和 pageSize 获取数据
}
}
}
</script>
自定义分页组件
如果需要完全自定义分页逻辑,可以手动实现:
<template>
<div class="pagination">
<button
@click="prevPage"
:disabled="currentPage === 1"
>
上一页
</button>
<span>第 {{ currentPage }} 页</span>
<button
@click="nextPage"
:disabled="currentPage === totalPages"
>
下一页
</button>
</div>
</template>
<script>
export default {
props: {
totalItems: Number,
itemsPerPage: Number
},
data() {
return {
currentPage: 1
}
},
computed: {
totalPages() {
return Math.ceil(this.totalItems / this.itemsPerPage)
}
},
methods: {
prevPage() {
if (this.currentPage > 1) {
this.currentPage--
this.$emit('page-changed', this.currentPage)
}
},
nextPage() {
if (this.currentPage < this.totalPages) {
this.currentPage++
this.$emit('page-changed', this.currentPage)
}
}
}
}
</script>
结合后端 API 分页
实际项目中,分页通常需要与后端 API 配合:
<template>
<div>
<ul>
<li v-for="item in items" :key="item.id">{{ item.name }}</li>
</ul>
<el-pagination
:current-page="pagination.page"
:page-size="pagination.limit"
:total="pagination.total"
@current-change="fetchData"
/>
</div>
</template>
<script>
import axios from 'axios'
export default {
data() {
return {
items: [],
pagination: {
page: 1,
limit: 10,
total: 0
}
}
},
created() {
this.fetchData()
},
methods: {
fetchData(page = 1) {
this.pagination.page = page
axios.get('/api/items', {
params: {
page: this.pagination.page,
limit: this.pagination.limit
}
}).then(response => {
this.items = response.data.items
this.pagination.total = response.data.total
})
}
}
}
</script>
前端数据分页
如果数据量不大,可以在前端完成分页:
<template>
<div>
<ul>
<li v-for="item in paginatedItems" :key="item.id">{{ item.name }}</li>
</ul>
<button @click="prevPage">上一页</button>
<button @click="nextPage">下一页</button>
</div>
</template>
<script>
export default {
data() {
return {
allItems: [], // 所有数据
currentPage: 1,
itemsPerPage: 5
}
},
computed: {
paginatedItems() {
const start = (this.currentPage - 1) * this.itemsPerPage
const end = start + this.itemsPerPage
return this.allItems.slice(start, end)
},
totalPages() {
return Math.ceil(this.allItems.length / this.itemsPerPage)
}
},
methods: {
prevPage() {
if (this.currentPage > 1) this.currentPage--
},
nextPage() {
if (this.currentPage < this.totalPages) this.currentPage++
}
}
}
</script>
关键点总结
- 确定分页方式:前端分页还是后端分页
- 计算总页数:
Math.ceil(totalItems / itemsPerPage) - 处理页码变化事件
- 根据当前页码获取对应数据
- 考虑边界情况(第一页和最后一页)
根据项目需求选择合适的实现方式,组件库提供现成方案更快捷,自定义组件灵活性更高。







