vue分页的实现
vue分页的实现
在Vue中实现分页功能通常涉及前端分页和后端分页两种方式。前端分页适用于数据量较小的情况,后端分页适用于大数据量场景。
前端分页实现
-
数据分片
使用slice方法对数组进行分片,结合当前页码和每页条数计算分页数据:computed: { paginatedData() { const start = (this.currentPage - 1) * this.pageSize; const end = start + this.pageSize; return this.data.slice(start, end); } } -
分页控件
通过v-for渲染页码按钮,绑定点击事件切换页码:<button v-for="page in totalPages" @click="currentPage = page" :class="{ active: currentPage === page }" > {{ page }} </button> -
总页数计算
根据数据总量和每页条数动态计算总页数:computed: { totalPages() { return Math.ceil(this.data.length / this.pageSize); } }
后端分页实现
-
API请求参数
调用接口时传递页码和每页条数参数:methods: { fetchData() { axios.get('/api/data', { params: { page: this.currentPage, size: this.pageSize } }).then(response => { this.data = response.data.list; this.total = response.data.total; }); } } -
监听页码变化
使用watch监听页码变化并重新请求数据:watch: { currentPage() { this.fetchData(); } } -
分页组件集成
推荐使用现成组件库如Element UI的el-pagination:<el-pagination @current-change="handlePageChange" :current-page="currentPage" :page-size="pageSize" :total="total" />
性能优化建议
-
防抖处理
频繁切换页码时添加防抖逻辑,避免重复请求:handlePageChange: debounce(function(page) { this.currentPage = page; }, 300) -
滚动加载
大数据量场景可结合无限滚动方案,监听滚动事件动态加载数据。 -
缓存策略
对已请求的页码数据进行缓存,减少重复请求。
完整示例代码
<template>
<div>
<table>
<tr v-for="item in paginatedData" :key="item.id">
<td>{{ item.name }}</td>
</tr>
</table>
<div class="pagination">
<button
v-for="page in totalPages"
@click="currentPage = page"
:class="{ active: currentPage === page }"
>
{{ page }}
</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
data: [], // 原始数据
currentPage: 1,
pageSize: 10
};
},
computed: {
paginatedData() {
const start = (this.currentPage - 1) * this.pageSize;
const end = start + this.pageSize;
return this.data.slice(start, end);
},
totalPages() {
return Math.ceil(this.data.length / this.pageSize);
}
}
};
</script>






