vue分页插件实现
Vue 分页插件实现方法
使用现成组件库(推荐)
Element UI、Ant Design Vue 等主流库已提供成熟分页组件,可直接集成:
<template>
<el-pagination
:current-page="currentPage"
:page-size="pageSize"
:total="total"
@current-change="handleCurrentChange"
/>
</template>
<script>
export default {
data() {
return {
currentPage: 1,
pageSize: 10,
total: 100
}
},
methods: {
handleCurrentChange(val) {
this.currentPage = val
this.fetchData()
}
}
}
</script>
自定义分页组件
如需完全自定义分页逻辑,可通过以下方式实现:
<template>
<div class="pagination">
<button
@click="prevPage"
:disabled="currentPage === 1"
>上一页</button>
<span v-for="page in pages" :key="page">
<button
@click="goToPage(page)"
:class="{ active: currentPage === page }"
>{{ page }}</button>
</span>
<button
@click="nextPage"
:disabled="currentPage === totalPages"
>下一页</button>
</div>
</template>
<script>
export default {
props: {
totalItems: Number,
itemsPerPage: Number,
},
computed: {
totalPages() {
return Math.ceil(this.totalItems / this.itemsPerPage)
},
pages() {
const range = []
for (let i = 1; i <= this.totalPages; i++) {
range.push(i)
}
return range
}
},
methods: {
goToPage(page) {
this.$emit('page-changed', page)
},
prevPage() {
if (this.currentPage > 1) {
this.goToPage(this.currentPage - 1)
}
},
nextPage() {
if (this.currentPage < this.totalPages) {
this.goToPage(this.currentPage + 1)
}
}
}
}
</script>
后端API配合实现
分页通常需要后端接口支持,常见参数格式:
axios.get('/api/data', {
params: {
page: currentPage,
size: pageSize
}
})
性能优化建议
- 对于大数据量采用虚拟滚动代替传统分页
- 添加页码输入跳转功能
- 实现每页条数动态调整
- 添加总页数/总条数显示
样式定制技巧
通过CSS变量或SCSS覆盖默认样式:
.pagination {
--active-color: #409eff;
}
.pagination button.active {
background-color: var(--active-color);
color: white;
}
以上方案可根据项目需求组合使用,现成组件库适合快速开发,自定义组件更适合特定UI需求。







