vue 分页如何实现
Vue 分页实现方法
基础分页实现
使用 v-for 渲染分页按钮,结合计算属性动态显示数据。假设 currentPage 是当前页码,totalPages 是总页数:
<template>
<div>
<ul>
<li v-for="item in paginatedData" :key="item.id">{{ item.name }}</li>
</ul>
<div class="pagination">
<button
v-for="page in totalPages"
:key="page"
@click="currentPage = page"
:class="{ active: currentPage === page }"
>
{{ page }}
</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
data: [], // 原始数据
currentPage: 1,
itemsPerPage: 10
};
},
computed: {
totalPages() {
return Math.ceil(this.data.length / this.itemsPerPage);
},
paginatedData() {
const start = (this.currentPage - 1) * this.itemsPerPage;
const end = start + this.itemsPerPage;
return this.data.slice(start, end);
}
}
};
</script>
使用第三方库
对于复杂分页需求,可以使用 vue-paginate 或 element-ui 的分页组件。以 element-ui 为例:
<template>
<div>
<el-table :data="paginatedData">
<!-- 表格列定义 -->
</el-table>
<el-pagination
@current-change="handleCurrentChange"
:current-page="currentPage"
:page-size="itemsPerPage"
:total="totalItems"
layout="prev, pager, next"
/>
</div>
</template>
<script>
export default {
data() {
return {
data: [],
currentPage: 1,
itemsPerPage: 10
};
},
computed: {
totalItems() {
return this.data.length;
},
paginatedData() {
const start = (this.currentPage - 1) * this.itemsPerPage;
const end = start + this.itemsPerPage;
return this.data.slice(start, end);
}
},
methods: {
handleCurrentChange(val) {
this.currentPage = val;
}
}
};
</script>
后端分页处理
当数据量较大时,建议通过 API 实现后端分页。通过传递 page 和 pageSize 参数获取分页数据:
methods: {
fetchData() {
axios.get('/api/items', {
params: {
page: this.currentPage,
pageSize: this.itemsPerPage
}
}).then(response => {
this.data = response.data.items;
this.totalItems = response.data.total;
});
}
}
分页样式优化
为分页按钮添加基础样式,提升用户体验:
.pagination {
display: flex;
justify-content: center;
margin-top: 20px;
}
.pagination button {
margin: 0 5px;
padding: 5px 10px;
border: 1px solid #ddd;
}
.pagination button.active {
background-color: #42b983;
color: white;
}






