vue前端分页怎么实现
Vue 前端分页实现方法
使用计算属性分页
通过计算属性对数据进行分页处理,适用于数据量较小的场景。
<template>
<div>
<table>
<tr v-for="item in paginatedData" :key="item.id">
<td>{{ item.name }}</td>
</tr>
</table>
<button @click="prevPage" :disabled="currentPage === 1">上一页</button>
<span>第 {{ currentPage }} 页</span>
<button @click="nextPage" :disabled="currentPage === pageCount">下一页</button>
</div>
</template>
<script>
export default {
data() {
return {
items: [], // 原始数据
currentPage: 1,
pageSize: 10
};
},
computed: {
pageCount() {
return Math.ceil(this.items.length / this.pageSize);
},
paginatedData() {
const start = (this.currentPage - 1) * this.pageSize;
const end = start + this.pageSize;
return this.items.slice(start, end);
}
},
methods: {
nextPage() {
if (this.currentPage < this.pageCount) {
this.currentPage++;
}
},
prevPage() {
if (this.currentPage > 1) {
this.currentPage--;
}
}
}
};
</script>
使用第三方库分页
对于更复杂的分页需求,可以使用第三方库如 vue-paginate 或 element-ui 的分页组件。

安装 element-ui 分页组件:
npm install element-ui
使用示例:

<template>
<div>
<el-table :data="paginatedData">
<el-table-column prop="name" label="名称"></el-table-column>
</el-table>
<el-pagination
@current-change="handleCurrentChange"
:current-page="currentPage"
:page-size="pageSize"
:total="totalItems"
layout="prev, pager, next">
</el-pagination>
</div>
</template>
<script>
import { Table, TableColumn, Pagination } from 'element-ui';
export default {
components: {
'el-table': Table,
'el-table-column': TableColumn,
'el-pagination': Pagination
},
data() {
return {
items: [],
currentPage: 1,
pageSize: 10,
totalItems: 0
};
},
computed: {
paginatedData() {
const start = (this.currentPage - 1) * this.pageSize;
const end = start + this.pageSize;
return this.items.slice(start, end);
}
},
methods: {
handleCurrentChange(page) {
this.currentPage = page;
}
},
mounted() {
this.totalItems = this.items.length;
}
};
</script>
后端分页结合前端展示
对于大数据量场景,通常采用后端分页,前端仅负责展示和页码控制。
<template>
<div>
<table>
<tr v-for="item in items" :key="item.id">
<td>{{ item.name }}</td>
</tr>
</table>
<el-pagination
@current-change="fetchData"
:current-page="currentPage"
:page-size="pageSize"
:total="totalItems"
layout="prev, pager, next">
</el-pagination>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
items: [],
currentPage: 1,
pageSize: 10,
totalItems: 0
};
},
methods: {
fetchData(page = 1) {
axios.get('/api/items', {
params: {
page,
size: this.pageSize
}
}).then(response => {
this.items = response.data.items;
this.totalItems = response.data.total;
this.currentPage = page;
});
}
},
mounted() {
this.fetchData();
}
};
</script>
分页样式优化
可以通过 CSS 美化分页组件,例如调整按钮间距、颜色等。
.el-pagination {
margin-top: 20px;
text-align: center;
}
.el-pagination button,
.el-pagination span {
margin: 0 5px;
}
以上方法覆盖了从简单到复杂的分页需求,开发者可根据项目实际情况选择合适方案。






