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">Previous</button>
<span>Page {{ currentPage }} of {{ totalPages }}</span>
<button @click="nextPage" :disabled="currentPage === totalPages">Next</button>
</div>
</template>
<script>
export default {
data() {
return {
allData: [], // 所有数据
currentPage: 1,
itemsPerPage: 10
}
},
computed: {
paginatedData() {
const start = (this.currentPage - 1) * this.itemsPerPage
const end = start + this.itemsPerPage
return this.allData.slice(start, end)
},
totalPages() {
return Math.ceil(this.allData.length / this.itemsPerPage)
}
},
methods: {
prevPage() {
this.currentPage--
},
nextPage() {
this.currentPage++
}
}
}
</script>
后端分页(推荐用于大数据量)
<template>
<div>
<ul>
<li v-for="item in items" :key="item.id">{{ item.name }}</li>
</ul>
<button @click="fetchData(currentPage - 1)" :disabled="currentPage === 1">Previous</button>
<span>Page {{ currentPage }} of {{ totalPages }}</span>
<button @click="fetchData(currentPage + 1)" :disabled="currentPage === totalPages">Next</button>
</div>
</template>
<script>
import axios from 'axios'
export default {
data() {
return {
items: [],
currentPage: 1,
itemsPerPage: 10,
totalPages: 1
}
},
methods: {
async fetchData(page) {
try {
const response = await axios.get('/api/items', {
params: {
page,
limit: this.itemsPerPage
}
})
this.items = response.data.items
this.totalPages = response.data.totalPages
this.currentPage = page
} catch (error) {
console.error(error)
}
}
},
created() {
this.fetchData(1)
}
}
</script>
使用第三方库
对于更复杂的分页需求,可以考虑使用现成的 Vue 分页组件:

-
安装
vuejs-paginate:npm install vuejs-paginate -
使用示例:

<template> <div> <paginate :page-count="totalPages" :click-handler="fetchData" :prev-text="'Prev'" :next-text="'Next'" :container-class="'pagination'" > </paginate> </div> </template>
export default { components: { Paginate }, // 其他逻辑同上 }
```样式定制
可以为分页组件添加自定义样式:
.pagination {
display: flex;
list-style: none;
padding: 0;
}
.pagination li {
margin: 0 5px;
cursor: pointer;
}
.pagination li.active {
font-weight: bold;
}
.pagination li.disabled {
opacity: 0.5;
cursor: not-allowed;
}
这些方法可以根据具体需求进行组合和调整,实现适合项目的分页功能。






