vue怎么实现分页查询
Vue 实现分页查询的方法
前端分页实现
使用 v-for 渲染分页数据,结合计算属性实现前端分页:
data() {
return {
currentPage: 1,
pageSize: 10,
totalItems: 100,
allItems: [] // 所有数据
}
},
computed: {
paginatedItems() {
const start = (this.currentPage - 1) * this.pageSize
const end = start + this.pageSize
return this.allItems.slice(start, end)
},
totalPages() {
return Math.ceil(this.totalItems / this.pageSize)
}
}
后端分页实现
通过 API 请求获取分页数据:
methods: {
fetchData() {
const params = {
page: this.currentPage,
size: this.pageSize
}
axios.get('/api/data', { params })
.then(response => {
this.paginatedItems = response.data.items
this.totalItems = response.data.total
})
},
handlePageChange(page) {
this.currentPage = page
this.fetchData()
}
}
分页组件使用
推荐使用 Element UI 的分页组件:
<el-pagination
@current-change="handlePageChange"
:current-page="currentPage"
:page-size="pageSize"
:total="totalItems"
layout="prev, pager, next">
</el-pagination>
自定义分页组件
实现简单分页控件:
<div class="pagination">
<button
@click="currentPage--"
:disabled="currentPage === 1">
上一页
</button>
<span>第 {{ currentPage }} 页</span>
<button
@click="currentPage++"
:disabled="currentPage >= totalPages">
下一页
</button>
</div>
分页优化技巧
添加 loading 状态提升用户体验:
data() {
return {
isLoading: false
}
},
methods: {
async fetchData() {
this.isLoading = true
try {
// API 调用
} finally {
this.isLoading = false
}
}
}
使用防抖减少频繁请求:
import { debounce } from 'lodash'
methods: {
handlePageChange: debounce(function(page) {
this.currentPage = page
this.fetchData()
}, 300)
}






