vue elemennt实现分页
Vue Element UI 分页实现
在 Vue 项目中结合 Element UI 实现分页功能,主要通过 el-pagination 组件完成。以下是具体实现方法:
安装 Element UI
确保项目已安装 Element UI,若未安装可通过以下命令安装:
npm install element-ui
引入 Element UI
在 main.js 或入口文件中全局引入:
import Vue from 'vue';
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
Vue.use(ElementUI);
分页组件使用
在 Vue 组件的模板中添加 el-pagination:
<template>
<div>
<!-- 表格数据展示 -->
<el-table :data="currentPageData" border>
<el-table-column prop="name" label="姓名"></el-table-column>
<el-table-column prop="age" label="年龄"></el-table-column>
</el-table>
<!-- 分页控件 -->
<el-pagination
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
:current-page="currentPage"
:page-sizes="[10, 20, 30, 40]"
:page-size="pageSize"
layout="total, sizes, prev, pager, next, jumper"
:total="totalData.length">
</el-pagination>
</div>
</template>
分页逻辑实现
在 Vue 组件的脚本中处理分页逻辑:
<script>
export default {
data() {
return {
totalData: [], // 所有数据
currentPageData: [], // 当前页数据
currentPage: 1, // 当前页码
pageSize: 10, // 每页条数
};
},
created() {
// 模拟数据加载
this.loadData();
},
methods: {
loadData() {
// 模拟从后端获取数据
this.totalData = Array.from({ length: 100 }, (_, i) => ({
name: `用户${i + 1}`,
age: Math.floor(Math.random() * 30) + 20,
}));
this.updatePageData();
},
updatePageData() {
// 根据当前页码和每页条数截取数据
const start = (this.currentPage - 1) * this.pageSize;
const end = start + this.pageSize;
this.currentPageData = this.totalData.slice(start, end);
},
handleSizeChange(val) {
// 每页条数变化
this.pageSize = val;
this.updatePageData();
},
handleCurrentChange(val) {
// 当前页码变化
this.currentPage = val;
this.updatePageData();
},
},
};
</script>
后端分页对接
若需与后端 API 交互,通常传递 currentPage 和 pageSize 参数:
methods: {
async fetchData() {
const res = await axios.get('/api/data', {
params: {
page: this.currentPage,
size: this.pageSize,
},
});
this.totalData = res.data.total;
this.currentPageData = res.data.list;
},
}
关键属性说明
current-page:绑定当前页码。page-sizes:可选每页条数配置。page-size:绑定每页显示条数。layout:控制分页组件的布局元素。total:绑定总数据量。
通过以上步骤即可实现完整的分页功能,支持前端分页或与后端交互的分页模式。







