vue如何实现分页显示
Vue实现分页显示的方法
使用Element UI的分页组件
Element UI提供了现成的分页组件el-pagination,适合快速集成到Vue项目中。安装Element UI后,可以直接在模板中使用:
<template>
<el-pagination
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
:current-page="currentPage"
:page-sizes="[10, 20, 30, 40]"
:page-size="pageSize"
layout="total, sizes, prev, pager, next, jumper"
:total="total">
</el-pagination>
</template>
<script>
export default {
data() {
return {
currentPage: 1,
pageSize: 10,
total: 100
};
},
methods: {
handleSizeChange(val) {
this.pageSize = val;
this.fetchData();
},
handleCurrentChange(val) {
this.currentPage = val;
this.fetchData();
},
fetchData() {
// 根据currentPage和pageSize请求数据
}
}
};
</script>
手动实现分页逻辑
如果不依赖UI库,可以通过计算属性手动实现分页。假设有一个数据数组items:
<template>
<div>
<ul>
<li v-for="item in paginatedItems" :key="item.id">{{ item.name }}</li>
</ul>
<button @click="prevPage" :disabled="currentPage === 1">上一页</button>
<span>第 {{ currentPage }} 页</span>
<button @click="nextPage" :disabled="currentPage >= totalPages">下一页</button>
</div>
</template>
<script>
export default {
data() {
return {
items: [], // 原始数据
currentPage: 1,
itemsPerPage: 5
};
},
computed: {
totalPages() {
return Math.ceil(this.items.length / this.itemsPerPage);
},
paginatedItems() {
const start = (this.currentPage - 1) * this.itemsPerPage;
const end = start + this.itemsPerPage;
return this.items.slice(start, end);
}
},
methods: {
prevPage() {
if (this.currentPage > 1) this.currentPage--;
},
nextPage() {
if (this.currentPage < this.totalPages) this.currentPage++;
}
}
};
</script>
结合后端API分页
实际项目中,分页通常与后端API配合。通过传递page和pageSize参数获取分页数据:
methods: {
async fetchData() {
const res = await axios.get('/api/items', {
params: {
page: this.currentPage,
pageSize: this.pageSize
}
});
this.items = res.data.items;
this.total = res.data.total;
}
}
使用第三方库
如果需要更复杂的分页功能,可以考虑以下库:
v-pagination:轻量级分页组件vuejs-paginate:简单易用的分页插件laravel-vue-pagination:专为Laravel后端设计
分页样式定制
通过CSS可以自定义分页样式。例如为手动实现的分页添加样式:
button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
ul {
list-style: none;
padding: 0;
}






