vue 实现翻页
Vue 实现翻页功能
在 Vue 中实现翻页功能通常需要结合分页组件和数据处理逻辑。以下是几种常见的实现方式:
使用 Element UI 的分页组件
安装 Element UI 后可以直接使用其分页组件:

<template>
<div>
<el-pagination
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
:current-page="currentPage"
:page-sizes="[10, 20, 30, 40]"
:page-size="pageSize"
layout="total, sizes, prev, pager, next, jumper"
:total="total">
</el-pagination>
</div>
</template>
<script>
export default {
data() {
return {
currentPage: 1,
pageSize: 10,
total: 100
}
},
methods: {
handleSizeChange(val) {
this.pageSize = val
this.fetchData()
},
handleCurrentChange(val) {
this.currentPage = val
this.fetchData()
},
fetchData() {
// 根据currentPage和pageSize获取数据
}
}
}
</script>
自定义分页组件
如果需要自定义分页组件,可以这样实现:
<template>
<div class="pagination">
<button
@click="prevPage"
:disabled="currentPage === 1">
上一页
</button>
<span>{{ currentPage }} / {{ totalPages }}</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 获取分页数据:

methods: {
async fetchData() {
try {
const response = await axios.get('/api/data', {
params: {
page: this.currentPage,
size: this.pageSize
}
})
this.dataList = response.data.items
this.total = response.data.total
} catch (error) {
console.error(error)
}
}
}
前端本地分页处理
如果数据量不大,可以在前端进行分页处理:
computed: {
paginatedData() {
const start = (this.currentPage - 1) * this.pageSize
const end = start + this.pageSize
return this.allData.slice(start, end)
},
totalPages() {
return Math.ceil(this.allData.length / this.pageSize)
}
}
样式优化
可以为分页组件添加基本样式:
.pagination {
display: flex;
justify-content: center;
align-items: center;
margin: 20px 0;
}
.pagination button {
margin: 0 10px;
padding: 5px 10px;
cursor: pointer;
}
.pagination button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
以上方法可以根据项目需求选择使用,Element UI 的分页组件适合快速开发,自定义组件则提供更多灵活性。实际应用中通常需要结合 API 请求实现完整的分页功能。






