最近在学分页功能,这里总结下前端如何实现分页
用的是element框架和el-pagination组件
效果图:
template代码:
table表格省略了,我让数据绑在tableData数组里
<el-pagination
:page-size="pageSize" // 设置每页显示多少条
@current-change="currentChangeHandle" // 当前页数改变时调用函数
:current-page="currentPage" // 当前第几页
layout="total, prev, pager, next"
:total="total" // 总共多少条信息
background>
</el-pagination>
script代码:
var pageNum
export default {
data () {
return {
total: 0,
pageSize: 5,
currentPage: 1,
totalPage: [{
id: '',
name: '',
sex: '',
birthday: '',
religon: '',
address: '',
note: ''
}],
tableData: [{
id: '',
name: '',
sex: '',
birthday: '',
religon: '',
address: '',
note: ''
}]
}
}
methods: {
currentChangeHandle (val) {
this.currentPage = val
this.getdata()
},
getdata () {
this.$axios.get('/user')
.then(response => {
console.log(response.data)
this.total = response.data.length
pageNum = Math.ceil(this.total / this.pageSize) || 1
this.totalPage = Object.keys(response.data).map(key => {
console.log(response.data)
return response.data[key]
})
for (let i = 0; i < pageNum; i++) {
this.tableData = this.totalPage.slice(this.pageSize * (this.currentPage - 1), this.pageSize * this.currentPage)
}
})
.catch(function (error) {
console.log(error)
})
}
}
以上是我的代码
整体思路 :
- 通过el-pagination组件设置好每页显示多少条,默认当前页,以及换页时的动作监听
- 从获取到的数组中选出想要展示在这个页面的子数组,将子数组赋给与表格绑定的数组(我的是tableData)。即
for (let i = 0; i < pageNum; i++) { this.tableData = this.totalPage.slice(this.pageSize * (this.currentPage - 1), this.pageSize * this.currentPage) }
要注意先判断获取到的数据是对象还是数组,比如我拿到的就是对象,所以我要先将对象转换为数组
this.totalPage = Object.keys(response.data).map(key => { console.log(response.data) return response.data[key] })
- currentChangeHandle方法,当前页数发生改变时,重新调用getdata()方法,将新的数组赋给tableData
currentChangeHandle (val) { this.currentPage = val this.getdata() console.log(`当前页: ${val} `) }
这样一个简单的分页就做好了。
感觉有一个缺点就是,每次换页都要从数据库获取一次全部数据。所以步骤2可以单独写一个方法,只要我们把获取到的数据存到一个数组里,每次换页只需要从这个数组取出对应的子数组,而不需要频繁调用数据库了。