vue分页功能的实现
实现基础分页功能
使用v-pagination组件配合数据切片实现基础分页。需要计算总页数和当前页显示的数据范围。
<template>
<div>
<ul>
<li v-for="item in paginatedData" :key="item.id">{{ item.name }}</li>
</ul>
<v-pagination
v-model="currentPage"
:length="totalPages"
></v-pagination>
</div>
</template>
<script>
export default {
data() {
return {
allData: [], // 全部数据
currentPage: 1,
itemsPerPage: 10
}
},
computed: {
totalPages() {
return Math.ceil(this.allData.length / this.itemsPerPage)
},
paginatedData() {
const start = (this.currentPage - 1) * this.itemsPerPage
const end = start + this.itemsPerPage
return this.allData.slice(start, end)
}
}
}
</script>
结合API实现后端分页
当数据量较大时,建议采用后端分页。通过API传递页码和每页条数参数。
methods: {
async fetchData() {
const params = {
page: this.currentPage,
size: this.itemsPerPage
}
const res = await axios.get('/api/data', { params })
this.paginatedData = res.data.items
this.totalItems = res.data.total
}
}
自定义分页样式
可以通过total-visible属性控制显示页码数量,使用prev-icon和next-icon自定义翻页按钮。
<v-pagination
v-model="currentPage"
:length="totalPages"
:total-visible="7"
prev-icon="mdi-chevron-left"
next-icon="mdi-chevron-right"
></v-pagination>
分页与表格组件结合
与v-data-table组件配合使用时,内置的分页功能更便捷。
<v-data-table
:items="items"
:headers="headers"
:items-per-page="10"
:page.sync="currentPage"
hide-default-footer
>
<template v-slot:footer>
<v-pagination
v-model="currentPage"
:length="pageCount"
></v-pagination>
</template>
</v-data-table>
分页器事件处理
监听分页变化事件,在页码改变时执行数据加载或其他操作。
watch: {
currentPage(newVal) {
this.fetchData()
window.scrollTo(0, 0) // 返回页面顶部
}
}






