vue中实现上下翻页
Vue 中实现上下翻页功能
使用 v-for 和数组切片
在 Vue 中可以通过维护当前页码和每页显示数量,结合数组切片实现翻页功能。定义 currentPage 和 itemsPerPage,通过计算属性 paginatedItems 返回当前页的数据。
data() {
return {
items: [], // 数据源
currentPage: 1,
itemsPerPage: 10
}
},
computed: {
paginatedItems() {
const start = (this.currentPage - 1) * this.itemsPerPage
const end = start + this.itemsPerPage
return this.items.slice(start, end)
}
},
methods: {
nextPage() {
if (this.currentPage * this.itemsPerPage < this.items.length) {
this.currentPage++
}
},
prevPage() {
if (this.currentPage > 1) {
this.currentPage--
}
}
}
使用分页组件
可以封装一个分页组件,通过 props 接收总条数和当前页,通过 emits 触发翻页事件。
// Pagination.vue
props: {
totalItems: Number,
currentPage: Number,
itemsPerPage: Number
},
computed: {
totalPages() {
return Math.ceil(this.totalItems / this.itemsPerPage)
}
},
methods: {
changePage(page) {
this.$emit('page-changed', page)
}
}
结合路由实现
在需要保存页码状态的场景,可以将页码作为路由参数。
// 路由配置
{
path: '/list/:page',
component: List
}
// 组件内
watch: {
'$route.params.page'(page) {
this.currentPage = Number(page) || 1
}
},
methods: {
changePage(page) {
this.$router.push(`/list/${page}`)
}
}
使用第三方库
对于复杂的分页需求,可以使用现成的分页库如 vuejs-paginate。
安装:
npm install vuejs-paginate
使用:
import Paginate from 'vuejs-paginate'
components: {
Paginate
},
methods: {
handlePageChange(page) {
this.currentPage = page
}
}
注意事项
- 处理边界情况,如第一页禁止上一页,最后一页禁止下一页
- 大量数据时考虑后端分页,避免前端性能问题
- 移动端可以考虑无限滚动代替传统分页
以上方法可根据具体需求选择或组合使用。数组切片适合前端少量数据分页,路由分页适合需要保存状态的场景,第三方库能快速实现标准分页样式。







