分页用vue实现
分页实现方法
使用Element UI的分页组件
安装Element UI库后,可以直接使用其分页组件。在Vue组件中引入el-pagination并配置相关属性。

<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() {
// 根据currentPage和pageSize获取数据
}
}
}
</script>
手动实现分页逻辑
如果不使用UI库,可以手动实现分页功能。通过计算属性对数据进行分页处理。

<template>
<div>
<ul>
<li v-for="item in paginatedData" :key="item.id">
{{ item.name }}
</li>
</ul>
<button @click="prevPage" :disabled="currentPage === 1">Previous</button>
<span>Page {{ currentPage }} of {{ totalPages }}</span>
<button @click="nextPage" :disabled="currentPage === totalPages">Next</button>
</div>
</template>
<script>
export default {
data() {
return {
currentPage: 1,
pageSize: 10,
items: [] // 原始数据
}
},
computed: {
totalPages() {
return Math.ceil(this.items.length / this.pageSize)
},
paginatedData() {
const start = (this.currentPage - 1) * this.pageSize
const end = start + this.pageSize
return this.items.slice(start, end)
}
},
methods: {
prevPage() {
if (this.currentPage > 1) {
this.currentPage--
}
},
nextPage() {
if (this.currentPage < this.totalPages) {
this.currentPage++
}
}
}
}
</script>
结合后端API实现分页
实际项目中,分页通常需要与后端API配合。前端传递页码和每页大小,后端返回对应数据。
<template>
<div>
<el-pagination
@current-change="handlePageChange"
:current-page="currentPage"
:page-size="pageSize"
layout="prev, pager, next"
:total="total">
</el-pagination>
</div>
</template>
<script>
export default {
data() {
return {
currentPage: 1,
pageSize: 10,
total: 0,
data: []
}
},
created() {
this.fetchData()
},
methods: {
fetchData() {
const params = {
page: this.currentPage,
size: this.pageSize
}
// 调用API获取数据
axios.get('/api/items', { params })
.then(response => {
this.data = response.data.items
this.total = response.data.total
})
},
handlePageChange(page) {
this.currentPage = page
this.fetchData()
}
}
}
</script>
使用Vue Paginate插件
Vue Paginate是一个轻量级的分页插件,适合简单场景。
<template>
<div>
<paginate
:page-count="totalPages"
:click-handler="changePage"
:prev-text="'Prev'"
:next-text="'Next'"
:container-class="'pagination'">
</paginate>
</div>
</template>
<script>
import Paginate from 'vuejs-paginate'
export default {
components: {
Paginate
},
data() {
return {
currentPage: 1,
totalPages: 10
}
},
methods: {
changePage(pageNum) {
this.currentPage = pageNum
this.fetchData()
}
}
}
</script>
以上方法可以根据项目需求选择适合的实现方式。Element UI的分页组件功能最全面,手动实现最灵活,后端API方式适合大数据量场景,Vue Paginate插件则适合简单需求。






