vue实现分页显示内容
Vue实现分页显示内容的方法
基础分页实现
在Vue中实现分页功能通常需要结合v-for指令和计算属性。定义一个currentPage变量表示当前页码,itemsPerPage表示每页显示的项目数。通过计算属性筛选当前页的数据:
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)
}
}
分页导航组件
创建一个分页导航组件,包含页码按钮和翻页控制:
<template>
<div class="pagination">
<button @click="prevPage" :disabled="currentPage === 1">上一页</button>
<span v-for="page in totalPages" :key="page">
<button @click="goToPage(page)" :class="{ active: page === currentPage }">
{{ page }}
</button>
</span>
<button @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
</div>
</template>
<script>
export default {
props: ['totalPages', 'currentPage'],
methods: {
prevPage() {
this.$emit('page-changed', this.currentPage - 1)
},
nextPage() {
this.$emit('page-changed', this.currentPage + 1)
},
goToPage(page) {
this.$emit('page-changed', page)
}
}
}
</script>
与后端API集成
当数据量较大时,应该实现后端分页。使用axios等HTTP客户端请求特定页码的数据:

methods: {
fetchData(page) {
axios.get(`/api/items?page=${page}&limit=${this.itemsPerPage}`)
.then(response => {
this.items = response.data.items
this.totalItems = response.data.total
})
}
}
使用第三方库
对于更复杂的需求,可以使用现成的分页组件库:
vue-paginate:轻量级分页插件element-ui的el-pagination:功能丰富的企业级分页组件v-pagination:简单易用的分页组件
安装示例:

npm install vue-paginate
使用示例:
import VuePaginate from 'vue-paginate'
Vue.use(VuePaginate)
// 模板中使用
<paginate
:page-count="totalPages"
:click-handler="fetchData"
:prev-text="'Prev'"
:next-text="'Next'"
:container-class="'pagination'">
</paginate>
样式优化
为分页组件添加CSS样式提升用户体验:
.pagination {
display: flex;
justify-content: center;
margin-top: 20px;
}
.pagination button {
margin: 0 5px;
padding: 5px 10px;
border: 1px solid #ddd;
background: #fff;
cursor: pointer;
}
.pagination button.active {
background: #42b983;
color: white;
border-color: #42b983;
}
.pagination button:disabled {
opacity: 0.5;
cursor: not-allowed;
}






