vue加载实现分页
Vue 分页实现方法
安装依赖(如需要)
若使用第三方分页组件(如 element-ui 或 vant),需提前安装对应库:
npm install element-ui # 以 Element UI 为例
基础分页实现
模板部分
使用 v-for 渲染分页数据,配合分页控件:
<template>
<div>
<ul>
<li v-for="item in paginatedData" :key="item.id">{{ item.name }}</li>
</ul>
<el-pagination
@current-change="handlePageChange"
:current-page="currentPage"
:page-size="pageSize"
:total="totalItems">
</el-pagination>
</div>
</template>
脚本部分 计算分页数据并处理翻页事件:
<script>
export default {
data() {
return {
allData: [], // 原始数据
currentPage: 1, // 当前页码
pageSize: 10, // 每页条数
};
},
computed: {
paginatedData() {
const start = (this.currentPage - 1) * this.pageSize;
const end = start + this.pageSize;
return this.allData.slice(start, end);
},
totalItems() {
return this.allData.length;
}
},
methods: {
handlePageChange(page) {
this.currentPage = page;
}
},
async created() {
// 模拟异步数据加载
this.allData = await fetchData();
}
};
</script>
后端分页实现
API 请求示例 当数据量较大时,建议采用后端分页:
methods: {
async fetchPaginatedData() {
const res = await axios.get('/api/items', {
params: {
page: this.currentPage,
size: this.pageSize
}
});
this.paginatedData = res.data.items;
this.totalItems = res.data.total;
},
handlePageChange(page) {
this.currentPage = page;
this.fetchPaginatedData();
}
}
分页样式优化
自定义分页样式 通过 CSS 调整分页组件外观:
.el-pagination {
margin-top: 20px;
text-align: center;
}
.el-pagination.is-background .el-pager li:not(.disabled).active {
background-color: #409EFF;
}
性能优化建议
- 大数据量时优先采用后端分页
- 使用
v-show替代v-if保持分页组件 DOM 存在 - 对静态数据添加缓存机制
- 移动端可考虑无限滚动模式(如
vue-infinite-loading)
常见问题处理
页码重置 切换筛选条件时需要重置页码:
watch: {
filterCondition() {
this.currentPage = 1;
this.fetchData();
}
}
边界情况处理 添加对空数据的判断:
paginatedData() {
return this.allData.length
? this.allData.slice(...)
: [];
}






