vue实现数据分页
Vue 实现数据分页的方法
使用计算属性分页
在 Vue 中,可以利用计算属性对数据进行分页处理。这种方法适用于前端分页,即一次性获取所有数据后在客户端进行分页。
data() {
return {
items: [], // 所有数据
currentPage: 1, // 当前页码
itemsPerPage: 10 // 每页显示数量
}
},
computed: {
paginatedItems() {
const start = (this.currentPage - 1) * this.itemsPerPage
const end = start + this.itemsPerPage
return this.items.slice(start, end)
},
totalPages() {
return Math.ceil(this.items.length / this.itemsPerPage)
}
}
使用后端 API 分页
对于大数据量,通常需要后端配合实现分页,前端只请求当前页的数据。
methods: {
async fetchData(page) {
const response = await axios.get('/api/items', {
params: {
page,
per_page: this.itemsPerPage
}
})
this.items = response.data.items
this.totalItems = response.data.total
}
},
created() {
this.fetchData(1)
}
使用第三方组件
Vue 生态中有许多优秀的分页组件,如 vue-paginate 或 element-ui 的分页组件。
安装 element-ui 分页组件:
<template>
<el-pagination
@current-change="handleCurrentChange"
:current-page="currentPage"
:page-size="itemsPerPage"
:total="totalItems"
layout="prev, pager, next">
</el-pagination>
</template>
<script>
export default {
methods: {
handleCurrentChange(val) {
this.currentPage = val
this.fetchData(val)
}
}
}
</script>
自定义分页组件
如果需要完全自定义分页组件,可以创建一个简单的分页控件:
<template>
<div class="pagination">
<button
@click="prevPage"
:disabled="currentPage === 1">
上一页
</button>
<span>第 {{ currentPage }} 页</span>
<button
@click="nextPage"
:disabled="currentPage >= totalPages">
下一页
</button>
</div>
</template>
<script>
export default {
props: ['currentPage', 'totalPages'],
methods: {
prevPage() {
this.$emit('page-changed', this.currentPage - 1)
},
nextPage() {
this.$emit('page-changed', this.currentPage + 1)
}
}
}
</script>
分页样式优化
为分页组件添加基本样式,提升用户体验:
.pagination {
display: flex;
justify-content: center;
margin: 20px 0;
}
.pagination button {
margin: 0 10px;
padding: 5px 10px;
cursor: pointer;
}
.pagination button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
以上方法可以根据实际项目需求选择使用,前端分页适合数据量小的场景,后端分页适合大数据量情况,第三方组件能快速实现功能,自定义组件则提供最大灵活性。







