vue实现简单分页
实现基础分页功能
在Vue中实现分页通常需要结合v-for指令和计算属性。以下是一个基础实现示例:
<template>
<div>
<ul>
<li v-for="item in paginatedData" :key="item.id">
{{ item.name }}
</li>
</ul>
<div class="pagination">
<button
@click="prevPage"
:disabled="currentPage === 1"
>
上一页
</button>
<span>第 {{ currentPage }} 页</span>
<button
@click="nextPage"
:disabled="currentPage === totalPages"
>
下一页
</button>
</div>
</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>
添加页码导航
扩展基础分页功能,显示可点击的页码:
<template>
<div class="pagination">
<button @click="changePage(1)" :disabled="currentPage === 1">
首页
</button>
<button
v-for="page in visiblePages"
:key="page"
@click="changePage(page)"
:class="{ active: currentPage === page }"
>
{{ page }}
</button>
<button @click="changePage(totalPages)" :disabled="currentPage === totalPages">
尾页
</button>
</div>
</template>
<script>
export default {
computed: {
visiblePages() {
const range = 2 // 显示当前页前后各2页
let start = Math.max(1, this.currentPage - range)
let end = Math.min(this.totalPages, this.currentPage + range)
if (this.currentPage - start < range) {
end = Math.min(this.totalPages, end + (range - (this.currentPage - start)))
}
if (end - this.currentPage < range) {
start = Math.max(1, start - (range - (end - this.currentPage)))
}
const pages = []
for (let i = start; i <= end; i++) {
pages.push(i)
}
return pages
}
},
methods: {
changePage(page) {
this.currentPage = page
}
}
}
</script>
与API结合的分页实现
当数据来自API时,通常需要后端返回分页信息:
async fetchData() {
try {
const response = await axios.get('/api/items', {
params: {
page: this.currentPage,
per_page: this.itemsPerPage
}
})
this.items = response.data.data
this.totalItems = response.data.total
} catch (error) {
console.error(error)
}
}
使用第三方组件库
对于更复杂的需求,可以考虑使用现成的分页组件:
<template>
<b-pagination
v-model="currentPage"
:total-rows="totalItems"
:per-page="itemsPerPage"
aria-controls="my-table"
></b-pagination>
</template>
<script>
import { BPagination } from 'bootstrap-vue'
export default {
components: {
BPagination
}
}
</script>
响应式分页设置
根据屏幕尺寸动态调整每页显示数量:
computed: {
itemsPerPage() {
return window.innerWidth < 768 ? 5 : 10
}
},
mounted() {
window.addEventListener('resize', this.handleResize)
},
beforeDestroy() {
window.removeEventListener('resize', this.handleResize)
},
methods: {
handleResize() {
// 触发重新计算
this.$forceUpdate()
}
}
以上实现方式可以根据具体项目需求进行组合和调整,核心思路是通过计算属性处理数据分片,通过方法控制页码变化。







