原生vue实现表格分页
原生 Vue 实现表格分页的方法
数据准备与分页逻辑
在 Vue 的 data 中定义表格数据和分页相关变量:
data() {
return {
tableData: [], // 全部数据
currentPage: 1, // 当前页码
pageSize: 10, // 每页显示条数
total: 0 // 总数据量
}
}
计算当前页数据
使用计算属性筛选当前页显示的数据:
computed: {
paginatedData() {
const start = (this.currentPage - 1) * this.pageSize
const end = start + this.pageSize
return this.tableData.slice(start, end)
}
}
分页控件实现
在模板中添加分页按钮和表格:
<template>
<div>
<table>
<tr v-for="(item, index) in paginatedData" :key="index">
<!-- 表格内容 -->
</tr>
</table>
<div class="pagination">
<button
@click="currentPage--"
:disabled="currentPage === 1">
上一页
</button>
<span>第 {{ currentPage }} 页</span>
<button
@click="currentPage++"
:disabled="currentPage >= Math.ceil(total / pageSize)">
下一页
</button>
</div>
</div>
</template>
样式优化(可选)
添加基础样式改善视觉效果:
.pagination {
margin-top: 20px;
display: flex;
gap: 10px;
align-items: center;
}
button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
异步数据加载
如果数据需要从接口获取:
methods: {
async fetchData() {
const res = await api.getData()
this.tableData = res.data
this.total = res.total
}
},
mounted() {
this.fetchData()
}
完整组件示例
export default {
data() {
return {
tableData: [],
currentPage: 1,
pageSize: 10,
total: 0
}
},
computed: {
paginatedData() {
const start = (this.currentPage - 1) * this.pageSize
const end = start + this.pageSize
return this.tableData.slice(start, end)
}
},
methods: {
async fetchData() {
const res = await api.getData()
this.tableData = res.data
this.total = res.total
}
},
mounted() {
this.fetchData()
}
}
注意事项
- 分页按钮的禁用状态需要根据当前页码动态计算
- 对于大数据量建议使用服务端分页
- 可以添加页码跳转功能增强用户体验







