vue里面怎么实现分页
Vue 分页实现方法
在 Vue 中实现分页功能通常需要结合前端分页逻辑和后端 API 支持(若数据量大)。以下是两种常见实现方式:
前端分页实现
适用于数据量较小的场景,直接在组件内处理分页逻辑:

<template>
<div>
<ul>
<li v-for="item in paginatedData" :key="item.id">{{ item.name }}</li>
</ul>
<button @click="prevPage" :disabled="currentPage === 1">Previous</button>
<span>Page {{ currentPage }} of {{ totalPages }}</span>
<button @click="nextPage" :disabled="currentPage === totalPages">Next</button>
</div>
</template>
<script>
export default {
data() {
return {
items: [], // 原始数据
currentPage: 1,
itemsPerPage: 10
};
},
computed: {
paginatedData() {
const start = (this.currentPage - 1) * this.itemsPerPage;
const end = start + this.itemsPerPage;
return this.items.slice(start, end);
},
totalPages() {
return Math.ceil(this.items.length / this.itemsPerPage);
}
},
methods: {
nextPage() {
if (this.currentPage < this.totalPages) {
this.currentPage++;
}
},
prevPage() {
if (this.currentPage > 1) {
this.currentPage--;
}
}
}
};
</script>
后端分页实现
适用于大数据量场景,通过 API 请求分页数据:

<template>
<!-- 同上 -->
</template>
<script>
export default {
data() {
return {
paginatedData: [],
currentPage: 1,
totalPages: 0,
itemsPerPage: 10
};
},
methods: {
fetchData() {
axios.get(`/api/items?page=${this.currentPage}&limit=${this.itemsPerPage}`)
.then(response => {
this.paginatedData = response.data.items;
this.totalPages = response.data.totalPages;
});
},
nextPage() {
if (this.currentPage < this.totalPages) {
this.currentPage++;
this.fetchData();
}
},
prevPage() {
if (this.currentPage > 1) {
this.currentPage--;
this.fetchData();
}
}
},
created() {
this.fetchData();
}
};
</script>
使用分页组件库
常见 UI 库如 Element UI、Vuetify 等提供现成分页组件:
<template>
<el-pagination
@current-change="handleCurrentChange"
:current-page="currentPage"
:page-size="itemsPerPage"
:total="totalItems">
</el-pagination>
</template>
<script>
export default {
methods: {
handleCurrentChange(val) {
this.currentPage = val;
this.fetchData();
}
}
};
</script>
分页样式优化
添加 CSS 样式增强用户体验:
.pagination {
display: flex;
justify-content: center;
margin-top: 20px;
}
.page-btn {
margin: 0 5px;
padding: 5px 10px;
cursor: pointer;
}
.disabled {
opacity: 0.5;
cursor: not-allowed;
}
关键点在于计算分页偏移量和处理页码变更事件。前端分页适合少量数据,后端分页适合大数据量场景。UI 组件库能快速实现标准化分页,而自定义实现则更灵活。






