vue实现翻页效果
实现基础翻页功能
在Vue中实现翻页效果通常需要结合v-for指令和计算属性。以下是一个基础实现示例:
<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 }} 页</span>
<button @click="nextPage" :disabled="currentPage >= totalPages">下一页</button>
</div>
</template>
<script>
export default {
data() {
return {
items: [...], // 你的数据数组
currentPage: 1,
itemsPerPage: 10
}
},
computed: {
totalPages() {
return Math.ceil(this.items.length / this.itemsPerPage)
},
paginatedData() {
const start = (this.currentPage - 1) * this.itemsPerPage
const end = start + this.itemsPerPage
return this.items.slice(start, end)
}
},
methods: {
nextPage() {
if (this.currentPage < this.totalPages) {
this.currentPage++
}
},
prevPage() {
if (this.currentPage > 1) {
this.currentPage--
}
}
}
}
</script>
使用分页组件库
对于更复杂的需求,可以考虑使用现成的Vue分页组件:
-
Element UI Pagination:
<el-pagination @current-change="handleCurrentChange" :current-page="currentPage" :page-size="pageSize" :total="totalItems"> </el-pagination> -
Vue Paginate:
npm install vue-paginate
import VuePaginate from 'vue-paginate'
Vue.use(VuePaginate)
<paginate
:page-count="totalPages"
:click-handler="changePage"
:prev-text="'上一页'"
:next-text="'下一页'">
</paginate>
实现带页码跳转的分页
对于需要直接跳转到指定页码的场景:
<input
type="number"
v-model.number="jumpPage"
min="1"
:max="totalPages">
<button @click="goToPage">跳转</button>
methods: {
goToPage() {
if (this.jumpPage >= 1 && this.jumpPage <= this.totalPages) {
this.currentPage = this.jumpPage
}
}
}
分页样式优化
为分页控件添加基本样式:
.pagination {
display: flex;
justify-content: center;
margin-top: 20px;
}
.pagination button {
margin: 0 5px;
padding: 5px 10px;
cursor: pointer;
}
.pagination button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
服务器端分页
当数据量很大时,需要实现服务器端分页:
methods: {
async fetchData(page) {
const response = await axios.get(`/api/items?page=${page}&size=${this.itemsPerPage}`)
this.items = response.data.items
this.totalItems = response.data.total
},
handlePageChange(page) {
this.fetchData(page)
}
}
分页与路由结合
将当前页码同步到URL路由:
watch: {
currentPage(newVal) {
this.$router.push({ query: { page: newVal } })
}
},
created() {
this.currentPage = parseInt(this.$route.query.page) || 1
}
响应式分页
根据屏幕尺寸调整每页显示数量:

data() {
return {
itemsPerPage: window.innerWidth < 768 ? 5 : 10
}
},
created() {
window.addEventListener('resize', this.handleResize)
},
methods: {
handleResize() {
this.itemsPerPage = window.innerWidth < 768 ? 5 : 10
}
}






