vue 实现翻页表
Vue 实现翻页表格
使用 Vue 实现翻页表格需要结合分页组件和数据展示组件。以下是实现步骤:
安装依赖
需要安装 element-ui 或 ant-design-vue 这类 UI 库,它们提供了现成的分页组件。
npm install element-ui
基础模板结构 创建一个包含表格和分页组件的 Vue 模板。
<template>
<div>
<el-table :data="tableData" border>
<el-table-column prop="id" label="ID"></el-table-column>
<el-table-column prop="name" label="Name"></el-table-column>
</el-table>
<el-pagination
@current-change="handleCurrentChange"
:current-page="currentPage"
:page-size="pageSize"
:total="total"
layout="prev, pager, next">
</el-pagination>
</div>
</template>
数据与分页逻辑 在 Vue 实例中定义数据和方法处理分页。
<script>
export default {
data() {
return {
tableData: [],
currentPage: 1,
pageSize: 10,
total: 0
}
},
methods: {
fetchData() {
// 模拟 API 请求
const mockData = Array.from({ length: 100 }, (_, i) => ({
id: i + 1,
name: `Item ${i + 1}`
}))
this.total = mockData.length
this.tableData = mockData.slice(
(this.currentPage - 1) * this.pageSize,
this.currentPage * this.pageSize
)
},
handleCurrentChange(val) {
this.currentPage = val
this.fetchData()
}
},
mounted() {
this.fetchData()
}
}
</script>
样式调整 根据需要调整表格和分页组件的样式。

<style scoped>
.el-pagination {
margin-top: 20px;
text-align: center;
}
</style>
自定义分页逻辑
如果不使用 UI 库,可以手动实现分页功能。
模板部分
<template>
<div>
<table>
<tr v-for="item in paginatedData" :key="item.id">
<td>{{ item.id }}</td>
<td>{{ item.name }}</td>
</tr>
</table>
<button @click="prevPage" :disabled="currentPage === 1">Previous</button>
<span>Page {{ currentPage }} of {{ totalPages }}</span>
<button @click="nextPage" :disabled="currentPage === totalPages">Next</button>
</div>
</template>
脚本部分

<script>
export default {
data() {
return {
tableData: Array.from({ length: 100 }, (_, i) => ({
id: i + 1,
name: `Item ${i + 1}`
})),
currentPage: 1,
pageSize: 10
}
},
computed: {
totalPages() {
return Math.ceil(this.tableData.length / this.pageSize)
},
paginatedData() {
const start = (this.currentPage - 1) * this.pageSize
const end = start + this.pageSize
return this.tableData.slice(start, end)
}
},
methods: {
prevPage() {
if (this.currentPage > 1) {
this.currentPage--
}
},
nextPage() {
if (this.currentPage < this.totalPages) {
this.currentPage++
}
}
}
}
</script>
服务器端分页
对于大量数据,建议使用服务器端分页。
API 请求示例
methods: {
async fetchData() {
const res = await axios.get('/api/items', {
params: {
page: this.currentPage,
size: this.pageSize
}
})
this.tableData = res.data.items
this.total = res.data.total
}
}
分页组件事件
<el-pagination
@current-change="fetchData"
@size-change="handleSizeChange">
</el-pagination>
methods: {
handleSizeChange(val) {
this.pageSize = val
this.fetchData()
}
}
以上方法提供了从基础到进阶的 Vue 翻页表格实现方案,可以根据项目需求选择适合的方式。






