vue实现换页
Vue实现分页功能的方法
使用Vue实现分页功能可以通过多种方式完成,以下是几种常见的方法:
使用Element UI的Pagination组件
安装Element UI库后,可以直接使用其提供的分页组件:
<template>
<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>
</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 v-for="page in pages" :key="page">
<button
@click="goToPage(page)"
:class="{ active: currentPage === page }">
{{ page }}
</button>
</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)
},
pages() {
const pages = []
for (let i = 1; i <= this.totalPages; i++) {
pages.push(i)
}
return pages
}
},
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)
}
},
goToPage(page) {
this.currentPage = page
this.$emit('page-changed', this.currentPage)
}
}
}
</script>
与后端API配合

实际应用中通常需要与后端API配合实现分页:
methods: {
async fetchData() {
try {
const response = await axios.get('/api/data', {
params: {
page: this.currentPage,
limit: this.pageSize
}
})
this.dataList = response.data.items
this.total = response.data.total
} catch (error) {
console.error(error)
}
}
}
使用Vue Router实现路由分页
对于基于路由的分页应用,可以使用Vue Router:
// 路由配置
{
path: '/page/:pageNumber',
component: PageComponent
}
// 组件内
watch: {
'$route.params.pageNumber'(newPage) {
this.currentPage = parseInt(newPage) || 1
this.fetchData()
}
}
选择哪种方法取决于项目需求,UI库提供现成组件可以快速实现,自定义组件灵活性更高,与后端API配合是最常见的实际应用场景。






