vue实现接口分页
Vue 实现接口分页的方法
在 Vue 中实现接口分页通常需要结合后端 API 和前端分页组件。以下是常见的实现方式:
使用 Element UI 的分页组件
安装 Element UI 后,可以使用 el-pagination 组件:
<template>
<div>
<el-table :data="tableData">
<!-- 表格列定义 -->
</el-table>
<el-pagination
@current-change="handlePageChange"
:current-page="currentPage"
:page-size="pageSize"
:total="total"
layout="prev, pager, next">
</el-pagination>
</div>
</template>
<script>
export default {
data() {
return {
tableData: [],
currentPage: 1,
pageSize: 10,
total: 0
}
},
methods: {
fetchData() {
const params = {
page: this.currentPage,
size: this.pageSize
}
axios.get('/api/data', { params })
.then(response => {
this.tableData = response.data.list
this.total = response.data.total
})
},
handlePageChange(page) {
this.currentPage = page
this.fetchData()
}
},
created() {
this.fetchData()
}
}
</script>
使用自定义分页逻辑
如果不使用 UI 库,可以手动实现分页:
<template>
<div>
<table>
<!-- 表格内容 -->
</table>
<div class="pagination">
<button @click="prevPage" :disabled="currentPage === 1">上一页</button>
<span>第 {{ currentPage }} 页</span>
<button @click="nextPage" :disabled="currentPage * pageSize >= total">下一页</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
currentPage: 1,
pageSize: 10,
total: 0,
data: []
}
},
methods: {
fetchData() {
axios.get(`/api/data?page=${this.currentPage}&size=${this.pageSize}`)
.then(res => {
this.data = res.data.items
this.total = res.data.total
})
},
prevPage() {
if (this.currentPage > 1) {
this.currentPage--
this.fetchData()
}
},
nextPage() {
if (this.currentPage * this.pageSize < this.total) {
this.currentPage++
this.fetchData()
}
}
}
}
</script>
使用 Vuex 管理分页状态
对于大型应用,可以使用 Vuex 集中管理分页状态:
// store.js
export default new Vuex.Store({
state: {
currentPage: 1,
pageSize: 10,
totalItems: 0,
items: []
},
mutations: {
SET_ITEMS(state, payload) {
state.items = payload.items
state.totalItems = payload.total
},
SET_PAGE(state, page) {
state.currentPage = page
}
},
actions: {
async fetchItems({ commit, state }) {
const res = await axios.get('/api/items', {
params: {
page: state.currentPage,
size: state.pageSize
}
})
commit('SET_ITEMS', {
items: res.data.items,
total: res.data.total
})
}
}
})
前端本地分页处理
如果数据量不大,可以在前端进行分页处理:
computed: {
paginatedData() {
const start = (this.currentPage - 1) * this.pageSize
const end = start + this.pageSize
return this.allData.slice(start, end)
},
totalPages() {
return Math.ceil(this.allData.length / this.pageSize)
}
}
分页优化技巧
- 添加加载状态指示器
- 实现防抖避免频繁请求
- 缓存已加载的页面数据
- 支持自定义每页显示数量
- 添加跳转到指定页功能
以上方法可以根据项目需求选择或组合使用。与后端配合时,确保 API 支持分页参数(通常为 page/size 或 offset/limit)。







