vue分页插件实现分页
Vue分页插件实现方法
在Vue项目中实现分页功能,可以通过第三方插件或自定义组件完成。以下是几种常见实现方式:
使用Element UI Pagination组件
安装Element UI后直接使用其分页组件:
<template>
<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="total">
</el-pagination>
</template>
<script>
export default {
data() {
return {
currentPage: 1,
pageSize: 10,
total: 100
}
},
methods: {
handleSizeChange(val) {
this.pageSize = val
this.fetchData()
},
handleCurrentChange(val) {
this.currentPage = val
this.fetchData()
},
fetchData() {
// 调用API获取数据
}
}
}
</script>
使用v-pagination插件
安装v-pagination插件:
npm install v-pagination
使用示例:
<template>
<pagination
v-model="currentPage"
:records="total"
:per-page="pageSize"
@paginate="fetchData"
/>
</template>
<script>
import Pagination from 'v-pagination'
export default {
components: {
Pagination
},
data() {
return {
currentPage: 1,
pageSize: 10,
total: 100
}
},
methods: {
fetchData() {
// 获取数据逻辑
}
}
}
</script>
自定义分页组件
创建可复用的分页组件:
<!-- Pagination.vue -->
<template>
<div class="pagination">
<button
@click="changePage(currentPage - 1)"
:disabled="currentPage === 1">
上一页
</button>
<span v-for="page in pages" :key="page">
<button
@click="changePage(page)"
:class="{ active: currentPage === page }">
{{ page }}
</button>
</span>
<button
@click="changePage(currentPage + 1)"
:disabled="currentPage === totalPages">
下一页
</button>
</div>
</template>
<script>
export default {
props: {
totalItems: Number,
itemsPerPage: Number,
currentPage: 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: {
changePage(page) {
if (page >= 1 && page <= this.totalPages) {
this.$emit('page-changed', page)
}
}
}
}
</script>
与后端API配合
分页通常需要后端支持,API请求示例:
async fetchData() {
const response = await axios.get('/api/items', {
params: {
page: this.currentPage,
size: this.pageSize
}
})
this.items = response.data.items
this.total = response.data.total
}
以上方法可根据项目需求选择适合的实现方式。第三方插件如Element UI提供了开箱即用的解决方案,自定义组件则更灵活可控。






