vue中实现翻页功能
使用 v-pagination 组件
Vue 的 v-pagination 组件(来自 Vuetify)提供了一种简单的方式实现翻页功能。安装 Vuetify 后,可以直接使用该组件。
<template>
<v-pagination
v-model="currentPage"
:length="totalPages"
@input="handlePageChange"
></v-pagination>
</template>
<script>
export default {
data() {
return {
currentPage: 1,
totalPages: 10,
};
},
methods: {
handlePageChange(page) {
this.currentPage = page;
// 触发数据加载逻辑
this.loadData();
},
loadData() {
// 根据 currentPage 加载对应页的数据
console.log(`Loading data for page ${this.currentPage}`);
},
},
};
</script>
自定义翻页组件
如果需要更灵活的翻页功能,可以自定义一个翻页组件。

<template>
<div class="pagination">
<button
@click="goToPage(currentPage - 1)"
:disabled="currentPage === 1"
>
上一页
</button>
<span>当前页: {{ currentPage }} / {{ totalPages }}</span>
<button
@click="goToPage(currentPage + 1)"
:disabled="currentPage === totalPages"
>
下一页
</button>
</div>
</template>
<script>
export default {
props: {
currentPage: {
type: Number,
required: true,
},
totalPages: {
type: Number,
required: true,
},
},
methods: {
goToPage(page) {
if (page >= 1 && page <= this.totalPages) {
this.$emit('page-change', page);
}
},
},
};
</script>
<style>
.pagination {
display: flex;
justify-content: center;
align-items: center;
gap: 10px;
}
</style>
结合 API 分页请求
在实际项目中,翻页通常需要与后端 API 交互。以下是一个结合 API 请求的示例。
<template>
<div>
<ul>
<li v-for="item in items" :key="item.id">{{ item.name }}</li>
</ul>
<v-pagination
v-model="currentPage"
:length="totalPages"
@input="fetchData"
></v-pagination>
</div>
</template>
<script>
export default {
data() {
return {
currentPage: 1,
totalPages: 0,
items: [],
};
},
created() {
this.fetchData();
},
methods: {
async fetchData() {
const response = await axios.get('/api/items', {
params: {
page: this.currentPage,
},
});
this.items = response.data.items;
this.totalPages = response.data.totalPages;
},
},
};
</script>
使用 Element UI 的 el-pagination
如果项目使用的是 Element UI,可以使用其内置的 el-pagination 组件。

<template>
<el-pagination
@current-change="handleCurrentChange"
:current-page="currentPage"
:page-size="pageSize"
:total="totalItems"
layout="prev, pager, next"
></el-pagination>
</template>
<script>
export default {
data() {
return {
currentPage: 1,
pageSize: 10,
totalItems: 100,
};
},
methods: {
handleCurrentChange(page) {
this.currentPage = page;
this.loadData();
},
loadData() {
// 加载数据逻辑
},
},
};
</script>
分页逻辑封装
可以将分页逻辑封装成一个可复用的 mixin。
// paginationMixin.js
export default {
data() {
return {
currentPage: 1,
pageSize: 10,
totalItems: 0,
};
},
methods: {
handlePageChange(page) {
this.currentPage = page;
this.loadData();
},
loadData() {
// 需要组件自行实现
},
},
};
在组件中使用:
<template>
<div>
<!-- 数据展示 -->
<v-pagination
v-model="currentPage"
:length="Math.ceil(totalItems / pageSize)"
@input="handlePageChange"
></v-pagination>
</div>
</template>
<script>
import paginationMixin from './paginationMixin';
export default {
mixins: [paginationMixin],
methods: {
loadData() {
// 实现具体的数据加载逻辑
},
},
};
</script>






