vue分页查询怎么实现
Vue分页查询实现方法
基础分页实现(前端分页)
适用于数据量较小的情况,直接在Vue组件中处理分页逻辑。
<template>
<div>
<table>
<tr v-for="item in paginatedData" :key="item.id">
<td>{{ item.name }}</td>
</tr>
</table>
<div class="pagination">
<button @click="prevPage" :disabled="currentPage === 1">上一页</button>
<span>第 {{ currentPage }} 页</span>
<button @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
allData: [], // 全部数据
currentPage: 1,
itemsPerPage: 10
}
},
computed: {
totalPages() {
return Math.ceil(this.allData.length / this.itemsPerPage)
},
paginatedData() {
const start = (this.currentPage - 1) * this.itemsPerPage
const end = start + this.itemsPerPage
return this.allData.slice(start, end)
}
},
methods: {
nextPage() {
if (this.currentPage < this.totalPages) {
this.currentPage++
}
},
prevPage() {
if (this.currentPage > 1) {
this.currentPage--
}
}
},
async created() {
// 获取所有数据
this.allData = await fetch('/api/items').then(res => res.json())
}
}
</script>
后端分页实现(推荐)
实际项目中更常见的实现方式,通过API请求实现分页。
<template>
<div>
<table>
<tr v-for="item in items" :key="item.id">
<td>{{ item.name }}</td>
</tr>
</table>
<div class="pagination">
<button @click="prevPage" :disabled="currentPage === 1">上一页</button>
<span>第 {{ currentPage }} 页</span>
<button @click="nextPage" :disabled="isLastPage">下一页</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [],
currentPage: 1,
itemsPerPage: 10,
totalItems: 0
}
},
computed: {
isLastPage() {
return this.items.length < this.itemsPerPage
}
},
methods: {
async fetchData() {
const response = await fetch(`/api/items?page=${this.currentPage}&limit=${this.itemsPerPage}`)
const data = await response.json()
this.items = data.items
this.totalItems = data.total
},
nextPage() {
this.currentPage++
this.fetchData()
},
prevPage() {
if (this.currentPage > 1) {
this.currentPage--
this.fetchData()
}
}
},
created() {
this.fetchData()
}
}
</script>
使用第三方组件库
Element UI的分页组件实现示例:
<template>
<div>
<el-table :data="tableData">
<el-table-column prop="name" label="名称"></el-table-column>
</el-table>
<el-pagination
@current-change="handleCurrentChange"
: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: {
handleCurrentChange(val) {
this.currentPage = val
this.fetchData()
},
async fetchData() {
const res = await this.$http.get('/api/items', {
params: {
page: this.currentPage,
size: this.pageSize
}
})
this.tableData = res.data.items
this.total = res.data.total
}
},
created() {
this.fetchData()
}
}
</script>
分页查询优化建议
- 添加加载状态提示
- 实现防抖处理快速翻页
- 缓存已请求过的页面数据
- 添加页码输入框跳转功能
- 实现URL同步当前页码
以上方法可根据实际项目需求选择或组合使用,后端分页是推荐的主流实现方式,特别是在数据量较大的情况下。







