vue实现分页功能
Vue 分页功能实现
在 Vue 中实现分页功能通常需要结合后端 API 或前端数据分页逻辑。以下是两种常见的实现方式:
前端分页实现
适用于数据量较小的情况,直接在 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">上一页</button>
<span>第 {{ currentPage }} 页 / 共 {{ totalPages }} 页</span>
<button @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
</div>
</div>
</template>
脚本部分:
<script>
export default {
data() {
return {
allData: [], // 所有数据
currentPage: 1,
itemsPerPage: 10
};
},
computed: {
paginatedData() {
const start = (this.currentPage - 1) * this.itemsPerPage;
const end = start + this.itemsPerPage;
return this.allData.slice(start, end);
},
totalPages() {
return Math.ceil(this.allData.length / this.itemsPerPage);
}
},
methods: {
prevPage() {
if (this.currentPage > 1) this.currentPage--;
},
nextPage() {
if (this.currentPage < this.totalPages) this.currentPage++;
}
},
async created() {
// 模拟获取数据
this.allData = Array.from({ length: 100 }, (_, i) => ({
id: i + 1,
name: `Item ${i + 1}`
}));
}
};
</script>
后端分页实现
适用于数据量大的情况,通过 API 请求分页数据。

模板部分:
<template>
<div>
<ul>
<li v-for="item in items" :key="item.id">{{ item.name }}</li>
</ul>
<div class="pagination">
<button @click="fetchData(currentPage - 1)" :disabled="currentPage === 1">上一页</button>
<span>第 {{ currentPage }} 页</span>
<button @click="fetchData(currentPage + 1)" :disabled="!hasNext">下一页</button>
</div>
</div>
</template>
脚本部分:
<script>
import axios from 'axios';
export default {
data() {
return {
items: [],
currentPage: 1,
hasNext: false
};
},
methods: {
async fetchData(page) {
try {
const response = await axios.get(`/api/items?page=${page}`);
this.items = response.data.items;
this.currentPage = page;
this.hasNext = response.data.hasNext;
} catch (error) {
console.error('Error fetching data:', error);
}
}
},
created() {
this.fetchData(1);
}
};
</script>
使用第三方库
对于更复杂的分页需求,可以考虑使用现成的 Vue 分页组件:

-
安装依赖:
npm install vuejs-paginate -
使用示例:
<template> <div> <paginate :page-count="totalPages" :click-handler="changePage" :prev-text="'Prev'" :next-text="'Next'" :container-class="'pagination'" /> </div> </template>
export default { components: { Paginate }, methods: { changePage(pageNum) { this.currentPage = pageNum; // 触发数据更新 } } };
```样式定制
可以为分页组件添加 CSS 样式:
.pagination {
display: flex;
justify-content: center;
margin-top: 20px;
}
.pagination button {
margin: 0 5px;
padding: 5px 10px;
cursor: pointer;
}
.pagination button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
以上方法可根据实际项目需求选择或组合使用。前端分页适合数据量小的场景,后端分页适合大数据量情况,第三方库可快速实现复杂分页功能。






