vue分页怎么实现
实现Vue分页的方法
使用Element UI的分页组件
Element UI提供了现成的分页组件el-pagination,适合快速集成。安装Element UI后,直接在模板中使用:
<template>
<el-pagination
@current-change="handleCurrentChange"
:current-page="currentPage"
:page-size="pageSize"
:total="total">
</el-pagination>
</template>
<script>
export default {
data() {
return {
currentPage: 1,
pageSize: 10,
total: 100
};
},
methods: {
handleCurrentChange(val) {
this.currentPage = val;
this.fetchData();
},
fetchData() {
// 根据currentPage和pageSize请求数据
}
}
};
</script>
自定义分页逻辑
如果需要完全自定义分页,可以通过计算属性实现数据切片:

<template>
<div>
<div v-for="item in paginatedData" :key="item.id">{{ item.name }}</div>
<button @click="prevPage">上一页</button>
<span>当前页: {{ currentPage }}</span>
<button @click="nextPage">下一页</button>
</div>
</template>
<script>
export default {
data() {
return {
currentPage: 1,
pageSize: 5,
allData: [] // 假设这是全部数据
};
},
computed: {
paginatedData() {
const start = (this.currentPage - 1) * this.pageSize;
const end = start + this.pageSize;
return this.allData.slice(start, end);
}
},
methods: {
prevPage() {
if (this.currentPage > 1) this.currentPage--;
},
nextPage() {
if (this.currentPage < this.totalPages) this.currentPage++;
}
},
computed: {
totalPages() {
return Math.ceil(this.allData.length / this.pageSize);
}
}
};
</script>
结合后端API分页
实际项目中,分页通常需要后端配合。通过API传递页码和每页条数参数:

methods: {
async fetchData() {
const res = await axios.get('/api/data', {
params: {
page: this.currentPage,
size: this.pageSize
}
});
this.listData = res.data.items;
this.total = res.data.total;
}
}
分页样式优化
可以通过CSS调整分页组件样式,或使用第三方库如v-pagination:
<v-pagination
v-model="currentPage"
:pages="totalPages"
:range-size="3"
active-color="#337ab7"
/>
分页与路由结合
在单页应用中,分页状态可通过路由参数同步:
watch: {
'$route.query.page'(val) {
this.currentPage = Number(val) || 1;
},
currentPage(val) {
this.$router.push({ query: { ...this.$route.query, page: val } });
}
}






