vue实现上下翻页
Vue实现上下翻页功能
数据准备与状态管理
在Vue组件中定义当前页码和总页数
data() {
return {
currentPage: 1,
totalPages: 10,
items: [] // 你的数据数组
}
}
翻页方法实现
向上翻页方法
methods: {
prevPage() {
if (this.currentPage > 1) {
this.currentPage--
this.loadPageData()
}
}
}
向下翻页方法

nextPage() {
if (this.currentPage < this.totalPages) {
this.currentPage++
this.loadPageData()
}
}
页面数据加载
实现数据加载逻辑
loadPageData() {
// 这里实现获取当前页数据的逻辑
// 可以是API调用或本地数据过滤
console.log(`加载第${this.currentPage}页数据`)
}
模板部分实现
在模板中添加翻页控制

<template>
<div class="pagination-container">
<button
@click="prevPage"
:disabled="currentPage === 1">
上一页
</button>
<span>当前页: {{ currentPage }} / {{ totalPages }}</span>
<button
@click="nextPage"
:disabled="currentPage === totalPages">
下一页
</button>
</div>
</template>
样式优化
添加基础样式增强用户体验
<style scoped>
.pagination-container {
display: flex;
justify-content: center;
align-items: center;
gap: 20px;
margin-top: 20px;
}
button {
padding: 8px 16px;
cursor: pointer;
}
button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
</style>
键盘事件支持
添加键盘上下箭头支持
mounted() {
window.addEventListener('keydown', this.handleKeyDown)
},
beforeDestroy() {
window.removeEventListener('keydown', this.handleKeyDown)
},
methods: {
handleKeyDown(e) {
if (e.key === 'ArrowUp') {
this.prevPage()
} else if (e.key === 'ArrowDown') {
this.nextPage()
}
}
}
性能优化建议
对于大数据量考虑分页加载
async loadPageData() {
try {
const response = await axios.get('/api/items', {
params: {
page: this.currentPage,
size: 10
}
})
this.items = response.data.items
this.totalPages = response.data.totalPages
} catch (error) {
console.error('加载数据失败:', error)
}
}





