vue实现对数据分页
分页实现的基本思路
在Vue中实现数据分页通常需要结合后端API或前端本地数据处理。核心逻辑包括计算总页数、当前页数据切片、页码切换事件处理等。以下提供两种常见实现方式。
前端本地分页实现
适用于数据量较小且已全部加载到前端的情况:

<template>
<div>
<table>
<tr v-for="item in paginatedData" :key="item.id">
<td>{{ item.name }}</td>
</tr>
</table>
<button @click="prevPage" :disabled="currentPage === 1">上一页</button>
<span>第 {{ currentPage }} 页 / 共 {{ totalPages }} 页</span>
<button @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
</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() {
this.currentPage += 1
},
prevPage() {
this.currentPage -= 1
}
}
}
</script>
后端API分页实现
适用于大数据量场景,需与后端配合:

<template>
<!-- 同上 -->
</template>
<script>
export default {
data() {
return {
paginatedData: [],
currentPage: 1,
totalPages: 0,
itemsPerPage: 10
}
},
mounted() {
this.fetchData()
},
methods: {
async fetchData() {
const res = await axios.get('/api/data', {
params: {
page: this.currentPage,
limit: this.itemsPerPage
}
})
this.paginatedData = res.data.items
this.totalPages = res.data.totalPages
},
nextPage() {
this.currentPage += 1
this.fetchData()
},
prevPage() {
this.currentPage -= 1
this.fetchData()
}
}
}
</script>
分页组件优化建议
添加页码跳转和每页条数选择功能可提升用户体验:
<template>
<select v-model="itemsPerPage" @change="handlePageSizeChange">
<option value="5">5条/页</option>
<option value="10">10条/页</option>
<option value="20">20条/页</option>
</select>
<input v-model="goToPage" type="number" min="1" :max="totalPages">
<button @click="jumpToPage">跳转</button>
</template>
<script>
export default {
data() {
return {
goToPage: 1,
itemsPerPage: 10
}
},
methods: {
handlePageSizeChange() {
this.currentPage = 1
this.fetchData()
},
jumpToPage() {
if (this.goToPage >= 1 && this.goToPage <= this.totalPages) {
this.currentPage = Number(this.goToPage)
this.fetchData()
}
}
}
}
</script>
第三方库方案
对于复杂需求,可考虑使用现成的分页组件库:
element-ui的el-paginationvant的van-paginationvuetify的v-pagination
这些组件通常提供更丰富的功能如页码显示样式定制、快速跳转等。






