分页用vue实现
分页功能实现(Vue)
基础分页组件
创建 Pagination.vue 组件:
<template>
<div class="pagination">
<button
@click="changePage(currentPage - 1)"
:disabled="currentPage === 1"
>上一页</button>
<span v-for="page in pages" :key="page">
<button
@click="changePage(page)"
:class="{ active: currentPage === page }"
>{{ page }}</button>
</span>
<button
@click="changePage(currentPage + 1)"
:disabled="currentPage === totalPages"
>下一页</button>
</div>
</template>
<script>
export default {
props: {
totalItems: Number,
itemsPerPage: {
type: Number,
default: 10
},
currentPage: {
type: Number,
default: 1
}
},
computed: {
totalPages() {
return Math.ceil(this.totalItems / this.itemsPerPage)
},
pages() {
const range = []
const start = Math.max(1, this.currentPage - 2)
const end = Math.min(this.totalPages, this.currentPage + 2)
for (let i = start; i <= end; i++) {
range.push(i)
}
return range
}
},
methods: {
changePage(page) {
if (page >= 1 && page <= this.totalPages) {
this.$emit('page-changed', page)
}
}
}
}
</script>
<style>
.pagination button {
margin: 0 5px;
padding: 5px 10px;
}
.pagination button.active {
background-color: #42b983;
color: white;
}
</style>
在父组件中使用
<template>
<div>
<!-- 数据列表 -->
<ul>
<li v-for="item in paginatedData" :key="item.id">
{{ item.name }}
</li>
</ul>
<!-- 分页组件 -->
<Pagination
:total-items="data.length"
:items-per-page="itemsPerPage"
:current-page="currentPage"
@page-changed="handlePageChange"
/>
</div>
</template>
<script>
import Pagination from './Pagination.vue'
export default {
components: { Pagination },
data() {
return {
data: [], // 从API获取的数据
itemsPerPage: 10,
currentPage: 1
}
},
computed: {
paginatedData() {
const start = (this.currentPage - 1) * this.itemsPerPage
const end = start + this.itemsPerPage
return this.data.slice(start, end)
}
},
methods: {
handlePageChange(page) {
this.currentPage = page
}
}
}
</script>
服务器端分页
当数据量很大时,建议使用服务器端分页:
methods: {
async fetchData(page) {
const response = await axios.get('/api/items', {
params: {
page,
per_page: this.itemsPerPage
}
})
this.data = response.data.items
this.totalItems = response.data.total
},
handlePageChange(page) {
this.currentPage = page
this.fetchData(page)
}
}
分页优化技巧
添加跳转输入框:
<input
type="number"
v-model.number="jumpPage"
min="1"
:max="totalPages"
@keyup.enter="changePage(jumpPage)"
>
<button @click="changePage(jumpPage)">跳转</button>
添加数据量选择器:
<select v-model="itemsPerPage" @change="handlePageSizeChange">
<option value="5">5条/页</option>
<option value="10">10条/页</option>
<option value="20">20条/页</option>
</select>
响应式分页控制
在移动端显示简化分页:

computed: {
pages() {
if (window.innerWidth < 768) {
return [this.currentPage]
} else {
const range = []
const start = Math.max(1, this.currentPage - 2)
const end = Math.min(this.totalPages, this.currentPage + 2)
for (let i = start; i <= end; i++) {
range.push(i)
}
return range
}
}
}






