vue实现网页分页
Vue 实现网页分页的方法
使用计算属性实现分页
在 Vue 中可以通过计算属性对数据进行分页处理。定义一个 currentPage 和 pageSize,利用计算属性返回当前页的数据。
data() {
return {
items: [], // 所有数据
currentPage: 1,
pageSize: 10
};
},
computed: {
paginatedItems() {
const start = (this.currentPage - 1) * this.pageSize;
const end = start + this.pageSize;
return this.items.slice(start, end);
}
}
分页组件实现
可以封装一个分页组件,通过 v-model 绑定当前页码,并触发父组件的页码变化事件。

<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,
pageSize: Number,
value: Number // v-model 绑定的当前页码
},
computed: {
totalPages() {
return Math.ceil(this.totalItems / this.pageSize);
},
currentPage: {
get() {
return this.value;
},
set(val) {
this.$emit('input', val);
}
}
},
methods: {
prevPage() {
if (this.currentPage > 1) {
this.currentPage--;
}
},
nextPage() {
if (this.currentPage < this.totalPages) {
this.currentPage++;
}
}
}
};
</script>
结合后端分页
如果数据量较大,通常需要后端分页。通过 API 传递当前页码和每页大小,后端返回对应数据。

methods: {
fetchData(page) {
axios.get('/api/items', {
params: {
page: page,
size: this.pageSize
}
}).then(response => {
this.items = response.data.items;
this.totalItems = response.data.total;
});
}
}
使用第三方库
可以使用现成的分页库如 vue-paginate 或 element-ui 的分页组件快速实现。
<template>
<el-pagination
@current-change="handlePageChange"
:current-page="currentPage"
:page-size="pageSize"
:total="totalItems"
layout="prev, pager, next">
</el-pagination>
</template>
<script>
import { ElPagination } from 'element-ui';
export default {
components: { ElPagination },
methods: {
handlePageChange(page) {
this.currentPage = page;
this.fetchData();
}
}
};
</script>
分页样式优化
可以通过 CSS 美化分页组件,例如添加悬停效果、调整间距等。
.pagination {
display: flex;
justify-content: center;
margin-top: 20px;
}
.pagination button {
margin: 0 5px;
padding: 5px 10px;
cursor: pointer;
}
.pagination button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
通过以上方法可以实现 Vue 中的网页分页功能,根据需求选择前端分页或后端分页方案。






