vue实现数据分页
Vue 实现数据分页的方法
使用计算属性分页
通过计算属性对数据进行切片处理,结合当前页码和每页条数动态计算显示范围:
data() {
return {
currentPage: 1,
itemsPerPage: 10,
allItems: [...] // 完整数据源
}
},
computed: {
paginatedItems() {
const start = (this.currentPage - 1) * this.itemsPerPage
const end = start + this.itemsPerPage
return this.allItems.slice(start, end)
},
totalPages() {
return Math.ceil(this.allItems.length / this.itemsPerPage)
}
}
使用第三方库
安装分页专用库如vuejs-paginate:
npm install vuejs-paginate
组件中使用:
import Paginate from 'vuejs-paginate'
export default {
components: { Paginate },
methods: {
changePage(pageNum) {
this.currentPage = pageNum
}
}
}
模板部分:
<paginate
:page-count="totalPages"
:click-handler="changePage"
:container-class="'pagination'"
></paginate>
服务端分页
当数据量较大时,建议采用API分页查询:
methods: {
async fetchPage(page) {
const res = await axios.get(`/api/items?page=${page}&limit=10`)
this.paginatedItems = res.data.items
this.totalCount = res.data.total
}
}
完整组件示例
<template>
<div>
<table>
<tr v-for="item in paginatedItems" :key="item.id">
<td>{{ item.name }}</td>
</tr>
</table>
<div class="pagination">
<button
v-for="page in totalPages"
:key="page"
@click="currentPage = page"
:class="{ active: currentPage === page }"
>
{{ page }}
</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
currentPage: 1,
itemsPerPage: 5,
allItems: [
// 示例数据
{id: 1, name: 'Item 1'},
{id: 2, name: 'Item 2'},
// ...更多数据
]
}
},
computed: {
paginatedItems() {
const start = (this.currentPage - 1) * this.itemsPerPage
const end = start + this.itemsPerPage
return this.allItems.slice(start, end)
},
totalPages() {
return Math.ceil(this.allItems.length / this.itemsPerPage)
}
}
}
</script>
<style>
.pagination button {
margin: 0 5px;
}
.pagination button.active {
font-weight: bold;
color: blue;
}
</style>
动态每页条数
添加选择器允许用户调整每页显示数量:
<select v-model="itemsPerPage">
<option value="5">5 per page</option>
<option value="10">10 per page</option>
<option value="20">20 per page</option>
</select>
性能优化建议
对于超大数据集(超过10万条),推荐:
- 使用虚拟滚动代替分页(如vue-virtual-scroller)
- 实现服务端分页+前端缓存
- 添加加载状态和错误处理
data() {
return {
isLoading: false,
error: null
}
},
methods: {
async loadPage(page) {
try {
this.isLoading = true
const data = await fetchPageData(page)
// 更新数据
} catch (err) {
this.error = err.message
} finally {
this.isLoading = false
}
}
}






