vue 实现分页
分页实现方法
在Vue中实现分页功能,可以通过计算属性和方法结合来实现。以下是一个典型的分页实现方式:
模板部分
<template>
<div>
<ul>
<li v-for="item in paginatedData" :key="item.id">
{{ item.name }}
</li>
</ul>
<div class="pagination">
<button @click="prevPage" :disabled="currentPage === 1">Previous</button>
<span>Page {{ currentPage }} of {{ totalPages }}</span>
<button @click="nextPage" :disabled="currentPage === totalPages">Next</button>
</div>
</div>
</template>
脚本部分
<script>
export default {
data() {
return {
items: [], // 你的数据数组
currentPage: 1,
itemsPerPage: 10
}
},
computed: {
totalPages() {
return Math.ceil(this.items.length / this.itemsPerPage)
},
paginatedData() {
const start = (this.currentPage - 1) * this.itemsPerPage
const end = start + this.itemsPerPage
return this.items.slice(start, end)
}
},
methods: {
nextPage() {
if (this.currentPage < this.totalPages) {
this.currentPage++
}
},
prevPage() {
if (this.currentPage > 1) {
this.currentPage--
}
}
}
}
</script>
使用第三方库
对于更复杂的分页需求,可以考虑使用专门的分页组件库:
-
vue-paginate:轻量级分页组件
npm install vue-paginate -
Element UI Pagination:如果你使用Element UI
<el-pagination layout="prev, pager, next" :total="1000" :page-size="10" @current-change="handleCurrentChange"> </el-pagination> -
Vuetify Pagination:Material Design风格的分页
<v-pagination v-model="page" :length="15" :total-visible="7" ></v-pagination>
服务器端分页
当数据量很大时,应该实现服务器端分页:
methods: {
fetchData(page) {
axios.get(`/api/items?page=${page}&limit=${this.itemsPerPage}`)
.then(response => {
this.items = response.data.items
this.totalItems = response.data.total
})
},
handlePageChange(page) {
this.currentPage = page
this.fetchData(page)
}
}
样式优化
为分页组件添加基本样式:
.pagination {
display: flex;
justify-content: center;
align-items: center;
margin-top: 20px;
}
.pagination button {
margin: 0 10px;
padding: 5px 10px;
cursor: pointer;
}
.pagination button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
高级功能实现
对于更高级的分页需求,可以添加以下功能:
- 页码跳转输入框
- 每页显示数量选择器
- 总记录数显示
- 首尾页快捷跳转按钮
这些功能可以通过扩展基本的分页组件来实现,根据具体需求调整计算属性和方法。







