vue实现分页表
Vue实现分页表格的方法
使用Element UI的分页组件
安装Element UI库后,可以通过el-table和el-pagination组件快速实现分页表格功能。
<template>
<div>
<el-table :data="tableData" border>
<el-table-column prop="date" label="日期"></el-table-column>
<el-table-column prop="name" label="姓名"></el-table-column>
</el-table>
<el-pagination
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
:current-page="currentPage"
:page-sizes="[10, 20, 30]"
:page-size="pageSize"
layout="total, sizes, prev, pager, next, jumper"
:total="total">
</el-pagination>
</div>
</template>
<script>
export default {
data() {
return {
tableData: [],
currentPage: 1,
pageSize: 10,
total: 0
}
},
methods: {
handleSizeChange(val) {
this.pageSize = val
this.fetchData()
},
handleCurrentChange(val) {
this.currentPage = val
this.fetchData()
},
fetchData() {
// 模拟API请求
const start = (this.currentPage - 1) * this.pageSize
const end = start + this.pageSize
this.tableData = mockData.slice(start, end)
this.total = mockData.length
}
},
created() {
this.fetchData()
}
}
</script>
自定义分页实现
如果不使用UI库,可以手动实现分页逻辑。
<template>
<div>
<table>
<tr v-for="item in paginatedData" :key="item.id">
<td>{{ item.name }}</td>
</tr>
</table>
<button @click="prevPage" :disabled="currentPage === 1">上一页</button>
<span>第{{ currentPage }}页</span>
<button @click="nextPage" :disabled="currentPage >= totalPages">下一页</button>
</div>
</template>
<script>
export default {
data() {
return {
allData: [],
currentPage: 1,
pageSize: 5
}
},
computed: {
totalPages() {
return Math.ceil(this.allData.length / this.pageSize)
},
paginatedData() {
const start = (this.currentPage - 1) * this.pageSize
const end = start + this.pageSize
return this.allData.slice(start, end)
}
},
methods: {
prevPage() {
this.currentPage--
},
nextPage() {
this.currentPage++
}
},
created() {
// 获取数据
this.allData = [...]
}
}
</script>
结合后端API的分页实现
实际项目中通常需要从后端获取分页数据。
methods: {
async fetchData() {
try {
const res = await axios.get('/api/data', {
params: {
page: this.currentPage,
size: this.pageSize
}
})
this.tableData = res.data.items
this.total = res.data.total
} catch (error) {
console.error(error)
}
}
}
分页器样式自定义
可以通过CSS对分页组件进行样式调整。
.el-pagination {
margin-top: 20px;
text-align: center;
}
这些方法提供了从简单到复杂的Vue分页表格实现方案,可根据项目需求选择合适的实现方式。







