vue 异步分页实现
异步分页实现方法
在Vue中实现异步分页通常需要结合后端API和前端分页组件。以下是常见的实现方式:
基础实现方案
-
使用
axios或其他HTTP库发起分页请求async fetchData(page = 1) { try { const response = await axios.get('/api/data', { params: { page, per_page: 10 } }); this.listData = response.data.data; this.total = response.data.total; } catch (error) { console.error(error); } } -
在组件生命周期中调用
created() { this.fetchData(); }
完整组件示例

<template>
<div>
<table>
<tr v-for="item in listData" :key="item.id">
<td>{{ item.name }}</td>
</tr>
</table>
<div class="pagination">
<button
v-for="page in totalPages"
:key="page"
@click="changePage(page)"
:class="{ active: currentPage === page }"
>
{{ page }}
</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
listData: [],
currentPage: 1,
perPage: 10,
total: 0
};
},
computed: {
totalPages() {
return Math.ceil(this.total / this.perPage);
}
},
methods: {
async fetchData() {
try {
const response = await axios.get('/api/data', {
params: {
page: this.currentPage,
per_page: this.perPage
}
});
this.listData = response.data.data;
this.total = response.data.total;
} catch (error) {
console.error(error);
}
},
changePage(page) {
this.currentPage = page;
this.fetchData();
}
},
created() {
this.fetchData();
}
};
</script>
优化方案
- 添加加载状态
data() { return { isLoading: false }; },
methods: { async fetchData() { this.isLoading = true; try { // ...请求代码 } finally { this.isLoading = false; } } }
2. 使用防抖减少频繁请求
```javascript
import { debounce } from 'lodash';
methods: {
fetchData: debounce(function() {
// 原fetchData实现
}, 300)
}
- 分页组件封装
可以创建独立的
Pagination组件,通过props和events与父组件通信
与Vuex结合

当应用状态管理使用Vuex时:
// store actions
async fetchPaginatedData({ commit }, { page, perPage }) {
const response = await axios.get('/api/data', { params: { page, perPage } });
commit('SET_DATA', response.data);
}
// 组件中
methods: {
changePage(page) {
this.$store.dispatch('fetchPaginatedData', {
page,
perPage: this.perPage
});
}
}
无限滚动方案
对于移动端或需要无限加载的场景:
mounted() {
window.addEventListener('scroll', this.handleScroll);
},
beforeDestroy() {
window.removeEventListener('scroll', this.handleScroll);
},
methods: {
handleScroll() {
const bottom = window.innerHeight + window.scrollY >= document.body.offsetHeight - 100;
if (bottom && !this.isLoading && this.currentPage < this.totalPages) {
this.currentPage++;
this.fetchData();
}
}
}
以上方案可根据实际项目需求进行组合和调整。关键点在于合理管理分页状态、处理异步请求以及优化用户体验。






