vue怎样实现分页
在Vue中实现分页功能
Vue中实现分页通常需要结合后端API和前端组件。以下是常见的实现方法:
使用Element UI的分页组件
安装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() {
// 调用API获取数据,传递currentPage和pageSize参数
}
}
}
</script>
自定义分页组件
如果需要自定义分页组件,可以这样实现:
<template>
<div class="pagination">
<button
@click="changePage(currentPage - 1)"
:disabled="currentPage === 1">
上一页
</button>
<span
v-for="page in pages"
:key="page"
@click="changePage(page)"
:class="{ active: currentPage === page }">
{{ page }}
</span>
<button
@click="changePage(currentPage + 1)"
:disabled="currentPage === totalPages">
下一页
</button>
</div>
</template>
<script>
export default {
props: {
totalItems: Number,
itemsPerPage: Number,
currentPage: Number
},
computed: {
totalPages() {
return Math.ceil(this.totalItems / this.itemsPerPage)
},
pages() {
const range = []
for (let i = 1; i <= this.totalPages; i++) {
range.push(i)
}
return range
}
},
methods: {
changePage(page) {
if (page >= 1 && page <= this.totalPages) {
this.$emit('page-changed', page)
}
}
}
}
</script>
结合后端API实现
通常分页需要后端支持,API调用示例:
methods: {
async fetchData() {
try {
const response = await axios.get('/api/data', {
params: {
page: this.currentPage,
size: this.pageSize
}
})
this.data = response.data.items
this.total = response.data.total
} catch (error) {
console.error(error)
}
}
}
分页样式优化
可以为分页组件添加CSS样式:
.pagination {
display: flex;
justify-content: center;
margin-top: 20px;
}
.pagination button {
margin: 0 5px;
padding: 5px 10px;
cursor: pointer;
}
.pagination span {
margin: 0 5px;
padding: 5px 10px;
cursor: pointer;
}
.pagination .active {
font-weight: bold;
color: #409EFF;
}
以上方法可以根据具体需求选择使用,Element UI的分页组件适合快速开发,自定义组件则提供更大的灵活性。后端API需要配合实现数据的分页查询功能。







