vue实现分页显示内容
Vue 实现分页显示内容的方法
使用计算属性实现分页逻辑
在 Vue 组件中定义一个计算属性,根据当前页码和每页显示数量切割数据数组。假设 items 是原始数据数组,currentPage 是当前页码,itemsPerPage 是每页显示数量:
computed: {
paginatedItems() {
const start = (this.currentPage - 1) * this.itemsPerPage;
const end = start + this.itemsPerPage;
return this.items.slice(start, end);
}
}
添加分页控制按钮
在模板中添加分页导航按钮,包括上一页、下一页和页码跳转:
<template>
<div>
<!-- 显示分页内容 -->
<div v-for="item in paginatedItems" :key="item.id">
{{ item.content }}
</div>
<!-- 分页控件 -->
<div class="pagination">
<button @click="prevPage" :disabled="currentPage === 1">上一页</button>
<span v-for="page in totalPages" :key="page">
<button
@click="currentPage = page"
:class="{ active: currentPage === page }"
>
{{ page }}
</button>
</span>
<button @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
</div>
</div>
</template>
计算总页数
添加一个计算属性来计算总页数:
computed: {
totalPages() {
return Math.ceil(this.items.length / this.itemsPerPage);
}
}
实现翻页方法
在 methods 中定义翻页方法:

methods: {
prevPage() {
if (this.currentPage > 1) {
this.currentPage--;
}
},
nextPage() {
if (this.currentPage < this.totalPages) {
this.currentPage++;
}
}
}
使用第三方库(可选)
对于更复杂的分页需求,可以使用第三方库如 vue-paginate:
-
安装库:

npm install vue-paginate -
在组件中使用:
import VuePaginate from 'vue-paginate' Vue.use(VuePaginate) -
模板中使用:
<paginate v-model="currentPage" :page-count="totalPages" :click-handler="changePage" :prev-text="'<'" :next-text="'>'" :container-class="'pagination'" :page-class="'page-item'"> </paginate>
样式定制
为分页组件添加基本样式:
.pagination {
display: flex;
justify-content: center;
margin-top: 20px;
}
.pagination button {
margin: 0 5px;
padding: 5px 10px;
cursor: pointer;
}
.pagination button.active {
background-color: #42b983;
color: white;
}
.pagination button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
完整组件示例
<template>
<div>
<div v-for="item in paginatedItems" :key="item.id">
{{ item.name }}
</div>
<div class="pagination">
<button @click="prevPage" :disabled="currentPage === 1">上一页</button>
<span v-for="page in totalPages" :key="page">
<button
@click="currentPage = page"
:class="{ active: currentPage === page }"
>
{{ page }}
</button>
</span>
<button @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [], // 从API获取或本地定义的数据
currentPage: 1,
itemsPerPage: 10
};
},
computed: {
paginatedItems() {
const start = (this.currentPage - 1) * this.itemsPerPage;
const end = start + this.itemsPerPage;
return this.items.slice(start, end);
},
totalPages() {
return Math.ceil(this.items.length / this.itemsPerPage);
}
},
methods: {
prevPage() {
if (this.currentPage > 1) this.currentPage--;
},
nextPage() {
if (this.currentPage < this.totalPages) this.currentPage++;
}
}
};
</script>





