vue实现上下翻页
vue实现上下翻页功能
使用v-for和数组切片
通过v-for渲染当前页数据,结合数组切片实现分页逻辑。data中定义当前页码和每页条数,计算属性返回当前页数据。
data() {
return {
list: [], // 全部数据
currentPage: 1,
pageSize: 10
}
},
computed: {
paginatedData() {
const start = (this.currentPage - 1) * this.pageSize
const end = start + this.pageSize
return this.list.slice(start, end)
}
},
methods: {
prevPage() {
if (this.currentPage > 1) this.currentPage--
},
nextPage() {
if (this.currentPage < this.totalPages) this.currentPage++
}
}
使用第三方分页组件
安装分页组件库如element-ui的Pagination组件,快速实现标准分页功能。
<template>
<el-pagination
@current-change="handleCurrentChange"
:current-page="currentPage"
:page-size="pageSize"
layout="prev, pager, next"
:total="total">
</el-pagination>
</template>
无限滚动加载
监听滚动事件,当滚动到底部时自动加载下一页数据,适合移动端场景。
mounted() {
window.addEventListener('scroll', this.handleScroll)
},
methods: {
handleScroll() {
const scrollY = window.scrollY
const visibleHeight = window.innerHeight
const pageHeight = document.documentElement.scrollHeight
const bottom = pageHeight - (scrollY + visibleHeight) < 50
if (bottom && !this.loading) {
this.loadNextPage()
}
}
}
路由参数分页
通过路由参数保存当前页码,实现可分享的分页链接。
watch: {
'$route.query.page'(newPage) {
this.currentPage = Number(newPage) || 1
}
},
methods: {
changePage(page) {
this.$router.push({
query: { ...this.$route.query, page }
})
}
}
键盘事件翻页
监听键盘上下箭头事件实现快捷翻页,提升用户体验。
mounted() {
document.addEventListener('keydown', this.handleKeyDown)
},
methods: {
handleKeyDown(e) {
if (e.key === 'ArrowUp') this.prevPage()
if (e.key === 'ArrowDown') this.nextPage()
}
}
每种实现方式适用于不同场景,可根据具体需求选择合适方案。数组切片方案适合简单列表,第三方组件提供完整分页功能,无限滚动适合移动端浏览,路由参数分页支持页面状态共享,键盘事件增强操作便捷性。







