vue实现新闻分页
实现新闻分页的步骤
后端API准备
确保后端提供分页查询接口,通常需要以下参数:
page: 当前页码pageSize: 每页显示数量 接口返回格式应包含:{ "data": [], "total": 100 }
前端组件结构
使用Vue组件管理分页功能,核心结构:
<template>
<div>
<NewsList :list="newsData" />
<Pagination
:current-page="currentPage"
:total="total"
@page-change="handlePageChange"
/>
</div>
</template>
数据获取方法
在Vue组件中实现数据获取逻辑:
async fetchNews() {
const res = await axios.get('/api/news', {
params: {
page: this.currentPage,
pageSize: this.pageSize
}
})
this.newsData = res.data.data
this.total = res.data.total
}
分页组件实现
创建可复用的分页组件:
<template>
<div class="pagination">
<button
v-for="page in pageCount"
:key="page"
@click="$emit('page-change', page)"
:class="{ active: page === currentPage }"
>
{{ page }}
</button>
</div>
</template>
<script>
export default {
props: {
currentPage: Number,
total: Number,
pageSize: {
type: Number,
default: 10
}
},
computed: {
pageCount() {
return Math.ceil(this.total / this.pageSize)
}
}
}
</script>
页面切换处理
在父组件中处理页码变更事件:
methods: {
handlePageChange(page) {
this.currentPage = page
this.fetchNews()
}
}
初始数据加载
在组件挂载时加载第一页数据:
mounted() {
this.fetchNews()
}
样式优化
添加基础样式提升用户体验:

.pagination {
display: flex;
gap: 8px;
margin-top: 20px;
}
.pagination button {
padding: 5px 10px;
cursor: pointer;
}
.pagination button.active {
background-color: #42b983;
color: white;
}
性能优化建议
- 添加加载状态提示
- 实现防抖处理快速翻页
- 考虑添加路由同步保持页面状态
- 对空数据状态进行处理






