vue实现换页
Vue实现分页功能
使用Vue实现分页功能通常涉及前端分页逻辑和后端API配合。以下是两种常见实现方式:
前端分页实现
适用于数据量较小的情况,所有数据一次性加载到前端:
<template>
<div>
<ul>
<li v-for="item in paginatedData" :key="item.id">{{ item.name }}</li>
</ul>
<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 {
currentPage: 1,
itemsPerPage: 10,
allItems: [] // 全部数据
}
},
computed: {
paginatedData() {
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)
}
},
methods: {
nextPage() {
if (this.currentPage < this.totalPages) {
this.currentPage++
}
},
prevPage() {
if (this.currentPage > 1) {
this.currentPage--
}
}
}
}
</script>
后端分页实现
适用于大数据量场景,通过API分页请求:
<template>
<!-- 同上 -->
</template>
<script>
export default {
data() {
return {
currentPage: 1,
itemsPerPage: 10,
paginatedItems: [],
totalItems: 0
}
},
computed: {
totalPages() {
return Math.ceil(this.totalItems / this.itemsPerPage)
}
},
methods: {
async fetchData() {
const res = await axios.get('/api/items', {
params: {
page: this.currentPage,
limit: this.itemsPerPage
}
})
this.paginatedItems = res.data.items
this.totalItems = res.data.total
},
nextPage() {
this.currentPage++
this.fetchData()
},
prevPage() {
this.currentPage--
this.fetchData()
}
},
created() {
this.fetchData()
}
}
</script>
使用第三方分页组件
Element UI分页组件示例:
<template>
<el-pagination
@current-change="handleCurrentChange"
:current-page="currentPage"
:page-size="pageSize"
:total="total"
layout="prev, pager, next">
</el-pagination>
</template>
<script>
export default {
data() {
return {
currentPage: 1,
pageSize: 10,
total: 100
}
},
methods: {
handleCurrentChange(val) {
this.currentPage = val
this.fetchData()
}
}
}
</script>
分页样式优化
可以添加跳转页码输入框:

<input v-model="goToPage" type="number" min="1" :max="totalPages">
<button @click="goToPageHandler">跳转</button>
methods: {
goToPageHandler() {
if (this.goToPage >= 1 && this.goToPage <= this.totalPages) {
this.currentPage = Number(this.goToPage)
this.fetchData()
}
}
}
以上实现可根据具体需求调整分页逻辑和UI样式。后端分页需要配合后端接口实现,通常接口需要支持page和limit参数。






