首先看问题:
解决方法:
只需要在之前的代码中添加以下两项就可以了。
totalPage: 0, // 总页数
// 计算出一共有多少页
this.totalPage = Math.ceil(this.total / this.queryObj.pagesize)
// 当前页码数大于了总页码数,就进行如下处理
if (this.queryObj.pagenum > this.totalPage) {
this.queryObj.pagenum = this.totalPage
this.getUserList()
}
<script>
export default {
data() {
return {
// 1.2 总数据条数
total: 0,
// 1.4 请求参数
queryObj: {
query: '',
pagenum: 1,
pagesize: 2
},
totalPage: 0, // 总页数
}
}
}
methods: {
// 1.4 请求用户数据的事件处理函数
async getUserList() {
const { data: res } = await this.$http.get('users', { params: this.queryObj })
if (res.meta.status !== 200) return this.$message.error('获取管理员列表成功')
this.userList = res.data.users
this.total = res.data.total
// 计算出一共有多少页
this.totalPage = Math.ceil(this.total / this.queryObj.pagesize)
// 当前页码数大于了总页码数,就进行如下处理
if (this.queryObj.pagenum > this.totalPage) {
this.queryObj.pagenum = this.totalPage
this.getUserList()
}
}
}
解决完成之后的效果:
也可以使用计算属性来做:
computed: {
// 总页数
totalPage() {
return Math.ceil(this.total / this.queryObj.pagesize)
}
},
methods: {
async getUserList() {
const { data: res } = await this.$http.get('users', { params: this.queryObj })
if (res.meta.status !== 200) return this.$message.error('获取管理员列表成功')
this.userList = res.data.users
this.total = res.data.total
if (this.queryObj.pagenum > this.totalPage) {
this.queryObj.pagenum = this.totalPage
this.getUserList()
}
}
}
感觉用计算属性来做更好一些。