vue 实现分页效果
使用 Element UI 实现分页
Element UI 提供了现成的分页组件 el-pagination,适合快速集成到 Vue 项目中。
安装 Element UI:
npm install element-ui
在 Vue 文件中引入并使用:
<template>
<div>
<el-pagination
@current-change="handleCurrentChange"
:current-page="currentPage"
:page-size="pageSize"
:total="total">
</el-pagination>
</div>
</template>
<script>
export default {
data() {
return {
currentPage: 1,
pageSize: 10,
total: 100
}
},
methods: {
handleCurrentChange(val) {
this.currentPage = val
// 这里可以调用接口或处理数据
}
}
}
</script>
自定义分页组件
如果需要完全自定义分页逻辑,可以通过计算属性实现分页数据切片。
定义分页逻辑:
<template>
<div>
<ul>
<li v-for="item in paginatedData" :key="item.id">{{ item.name }}</li>
</ul>
<button @click="prevPage">上一页</button>
<span>当前页: {{ currentPage }}</span>
<button @click="nextPage">下一页</button>
</div>
</template>
<script>
export default {
data() {
return {
currentPage: 1,
pageSize: 5,
items: [
{ id: 1, name: 'Item 1' },
// ...更多数据
]
}
},
computed: {
paginatedData() {
const start = (this.currentPage - 1) * this.pageSize
const end = start + this.pageSize
return this.items.slice(start, end)
}
},
methods: {
nextPage() {
if (this.currentPage * this.pageSize < this.items.length) {
this.currentPage++
}
},
prevPage() {
if (this.currentPage > 1) {
this.currentPage--
}
}
}
}
</script>
结合后端 API 分页
实际项目中通常需要与后端 API 配合实现分页。
示例 API 调用:
<script>
export default {
data() {
return {
currentPage: 1,
pageSize: 10,
total: 0,
items: []
}
},
created() {
this.fetchData()
},
methods: {
async fetchData() {
const res = await axios.get('/api/items', {
params: {
page: this.currentPage,
size: this.pageSize
}
})
this.items = res.data.items
this.total = res.data.total
},
handlePageChange(page) {
this.currentPage = page
this.fetchData()
}
}
}
</script>
使用 Vue Router 实现 URL 分页
对于需要保持分页状态的场景,可以将页码存储在 URL 中。
路由配置:
// router.js
{
path: '/items/:page?',
component: ItemsList
}
组件实现:
<script>
export default {
watch: {
'$route.params.page'(newPage) {
this.currentPage = Number(newPage) || 1
this.fetchData()
}
},
methods: {
changePage(page) {
this.$router.push(`/items/${page}`)
}
}
}
</script>






