用vue实现加载分页
使用Vue实现分页加载
安装依赖
确保项目中已安装axios用于数据请求,若未安装可通过以下命令安装:
npm install axios
基本分页组件结构
在Vue组件中定义分页所需的数据和方法:

<template>
<div>
<ul>
<li v-for="item in items" :key="item.id">{{ item.name }}</li>
</ul>
<div class="pagination">
<button @click="prevPage" :disabled="currentPage === 1">上一页</button>
<span>当前页: {{ currentPage }}</span>
<button @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
</div>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
items: [],
currentPage: 1,
totalPages: 1,
perPage: 10
};
},
methods: {
fetchData() {
axios.get(`/api/items?page=${this.currentPage}&per_page=${this.perPage}`)
.then(response => {
this.items = response.data.data;
this.totalPages = response.data.total_pages;
});
},
nextPage() {
if (this.currentPage < this.totalPages) {
this.currentPage++;
this.fetchData();
}
},
prevPage() {
if (this.currentPage > 1) {
this.currentPage--;
this.fetchData();
}
}
},
created() {
this.fetchData();
}
};
</script>
后端API示例
假设后端使用类似RESTful的接口,返回格式如下:
{
"data": [...],
"total_pages": 5
}
优化加载体验
添加加载状态提示,避免用户重复点击:

data() {
return {
isLoading: false
};
},
methods: {
fetchData() {
this.isLoading = true;
axios.get(...)
.then(...)
.finally(() => {
this.isLoading = false;
});
}
}
分页样式优化
使用CSS美化分页按钮,例如:
.pagination {
margin-top: 20px;
}
.pagination button {
padding: 5px 10px;
margin: 0 5px;
}
.pagination button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
动态页码显示
扩展分页组件,显示更多页码选项:
<template>
<div class="pagination">
<button @click="goToPage(1)" :disabled="currentPage === 1">首页</button>
<button v-for="page in visiblePages"
@click="goToPage(page)"
:class="{ active: currentPage === page }">
{{ page }}
</button>
<button @click="goToPage(totalPages)" :disabled="currentPage === totalPages">末页</button>
</div>
</template>
computed: {
visiblePages() {
const range = 2; // 显示当前页前后各2页
let start = Math.max(1, this.currentPage - range);
let end = Math.min(this.totalPages, this.currentPage + range);
return Array.from({ length: end - start + 1 }, (_, i) => start + i);
}
}






