vue中如何实现分页
实现基础分页功能
在Vue中实现分页通常需要结合后端API返回的分页数据。前端主要处理页码切换、数据请求和UI渲染。使用v-for循环渲染分页按钮,通过计算属性动态生成页码数组:
<template>
<div>
<ul>
<li v-for="item in currentPageData" :key="item.id">{{ item.name }}</li>
</ul>
<div class="pagination">
<button @click="prevPage" :disabled="currentPage === 1">上一页</button>
<button
v-for="page in pageNumbers"
:key="page"
@click="goToPage(page)"
:class="{ active: currentPage === page }"
>
{{ page }}
</button>
<button @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
allData: [], // 所有数据
currentPage: 1, // 当前页码
pageSize: 10, // 每页条数
totalItems: 0 // 总数据量
}
},
computed: {
totalPages() {
return Math.ceil(this.totalItems / this.pageSize)
},
currentPageData() {
const start = (this.currentPage - 1) * this.pageSize
const end = start + this.pageSize
return this.allData.slice(start, end)
},
pageNumbers() {
const range = []
for (let i = 1; i <= this.totalPages; i++) {
range.push(i)
}
return range
}
},
methods: {
prevPage() {
if (this.currentPage > 1) this.currentPage--
},
nextPage() {
if (this.currentPage < this.totalPages) this.currentPage++
},
goToPage(page) {
this.currentPage = page
}
}
}
</script>
结合API请求实现动态分页
实际项目中通常需要从后端API获取分页数据。使用axios等HTTP库发送请求时,将当前页码和每页大小作为参数:
methods: {
async fetchData() {
try {
const response = await axios.get('/api/items', {
params: {
page: this.currentPage,
size: this.pageSize
}
})
this.allData = response.data.items
this.totalItems = response.data.total
} catch (error) {
console.error('获取数据失败:', error)
}
},
goToPage(page) {
this.currentPage = page
this.fetchData()
}
},
created() {
this.fetchData()
}
优化分页UI体验
对于数据量大的情况,可以改进分页按钮的显示方式,避免展示过多页码。常见做法是显示当前页前后各2页,其余用省略号表示:
computed: {
pageNumbers() {
const range = []
const start = Math.max(1, this.currentPage - 2)
const end = Math.min(this.totalPages, this.currentPage + 2)
if (start > 1) range.push(1)
if (start > 2) range.push('...')
for (let i = start; i <= end; i++) {
range.push(i)
}
if (end < this.totalPages - 1) range.push('...')
if (end < this.totalPages) range.push(this.totalPages)
return range
}
}
使用第三方分页组件
Vue生态中有许多成熟的分页组件可供选择,如Element UI的Pagination组件:
<template>
<el-pagination
@current-change="handleCurrentChange"
:current-page="currentPage"
:page-size="pageSize"
:total="totalItems"
layout="prev, pager, next">
</el-pagination>
</template>
<script>
import { ElPagination } from 'element-plus'
export default {
components: { ElPagination },
methods: {
handleCurrentChange(val) {
this.currentPage = val
this.fetchData()
}
}
}
</script>
处理分页查询参数
在需要保持分页状态的路由应用中,可以将分页参数同步到URL查询字符串中:
watch: {
currentPage(newVal) {
this.$router.push({
query: { ...this.$route.query, page: newVal }
})
}
},
created() {
if (this.$route.query.page) {
this.currentPage = Number(this.$route.query.page)
}
this.fetchData()
}






