vue分页代码实现
Vue 分页代码实现
在 Vue 中实现分页功能通常需要结合后端 API 返回的数据和前端的分页组件。以下是一个完整的实现示例,包括分页组件的封装和与后端数据的交互。
分页组件封装
创建一个可复用的分页组件 Pagination.vue:
<template>
<div class="pagination">
<button
@click="changePage(currentPage - 1)"
:disabled="currentPage === 1"
>
上一页
</button>
<span v-for="page in pages" :key="page">
<button
@click="changePage(page)"
:class="{ active: currentPage === page }"
>
{{ page }}
</button>
</span>
<button
@click="changePage(currentPage + 1)"
:disabled="currentPage === totalPages"
>
下一页
</button>
</div>
</template>
<script>
export default {
props: {
currentPage: {
type: Number,
required: true
},
totalPages: {
type: Number,
required: true
},
maxVisiblePages: {
type: Number,
default: 5
}
},
computed: {
pages() {
const range = [];
const start = Math.max(1, this.currentPage - Math.floor(this.maxVisiblePages / 2));
const end = Math.min(this.totalPages, start + this.maxVisiblePages - 1);
for (let i = start; i <= end; i++) {
range.push(i);
}
return range;
}
},
methods: {
changePage(page) {
if (page >= 1 && page <= this.totalPages) {
this.$emit('page-change', page);
}
}
}
};
</script>
<style scoped>
.pagination {
display: flex;
justify-content: center;
gap: 5px;
margin-top: 20px;
}
button {
padding: 5px 10px;
cursor: pointer;
}
button:disabled {
cursor: not-allowed;
opacity: 0.5;
}
.active {
background-color: #42b983;
color: white;
}
</style>
在父组件中使用分页
假设有一个列表页面需要分页展示数据:
<template>
<div>
<ul>
<li v-for="item in items" :key="item.id">
{{ item.name }}
</li>
</ul>
<Pagination
:current-page="currentPage"
:total-pages="totalPages"
@page-change="fetchData"
/>
</div>
</template>
<script>
import Pagination from './Pagination.vue';
export default {
components: {
Pagination
},
data() {
return {
items: [],
currentPage: 1,
totalPages: 1,
pageSize: 10
};
},
created() {
this.fetchData();
},
methods: {
async fetchData(page = 1) {
this.currentPage = page;
try {
const response = await axios.get('/api/items', {
params: {
page: this.currentPage,
size: this.pageSize
}
});
this.items = response.data.items;
this.totalPages = Math.ceil(response.data.total / this.pageSize);
} catch (error) {
console.error('Error fetching data:', error);
}
}
}
};
</script>
后端 API 接口示例
后端需要提供支持分页的接口,例如使用 Spring Boot:
@GetMapping("/api/items")
public ResponseEntity<PageResult<Item>> getItems(
@RequestParam(defaultValue = "1") int page,
@RequestParam(defaultValue = "10") int size) {
Page<Item> itemPage = itemRepository.findAll(PageRequest.of(page - 1, size));
PageResult<Item> result = new PageResult<>(
itemPage.getContent(),
itemPage.getTotalElements()
);
return ResponseEntity.ok(result);
}
分页逻辑说明
currentPage表示当前页码,从 1 开始totalPages表示总页数,通过总记录数除以每页大小计算得出maxVisiblePages控制分页组件中显示的最大页码数量changePage方法处理页码变更事件,触发父组件的fetchData方法
注意事项
- 分页组件应保持独立,不直接依赖具体业务逻辑
- 页码计算时注意边界情况(如第一页和最后一页)
- 分页请求应包含必要的错误处理
- 对于大数据量,考虑使用无限滚动替代传统分页
以上实现可以根据实际需求进行调整,例如添加每页大小选择器、跳转到指定页码等功能。







