一样平常来说呢,管理的数据很多是列表数据,列表数据就常会涌现分页功能,而分页功能基本上在以下情形中会调用列表接口
页面初始化查询的按钮分页的页码改变分页的长度改变本文章所分享的基于vue的mixin(代码混入)在实际项目中如何减少代码量,让我们的分页功能简洁高效,不须要在每个页面中写重复的代码
详细步骤:

一、 首先在src下创建mixin文件夹 (其可书写的格式与.vue文件中的script部分)
二、将其全局混入到main.js
import mixin from './mixin/index'Vue.mixin(mixin)三、在mixin.js中定义两个变量
queryParams:{} =>紧张用来存放列表接口的查询条件的参数PAGINATION: {pageSize: 20,currentPage: 1,total: 0},=》是element-ui等分页组件( el-pagination)的初始化参数四、mixin 中的methods定义好触发分页的事宜方法
//查询按钮
check() {
this.PAGINATION = {
...this.PAGINATION,
currentPage: 1
}
this.queryParams = this.getParams()
this.useMethod()
},
// 分页长度改变
handleSizeChange(pageSize) {
this.PAGINATION = {
...this.PAGINATION,
pageSize
}
this.queryParams = {
...this.queryParams,
offset: this.PAGINATION.pageSize
}
this.useMethod()
},
//分页页码改变
handleCurrentChange(currentPage) {
this.PAGINATION = {
...this.PAGINATION,
currentPage
}
this.queryParams = {
...this.queryParams,
page: this.PAGINATION.currentPage
}
this.useMethod()
},
上面的this.useMethod()是我们mixin处理分页功能的核心五、利用this.useMethod()方法让我们调用不同的分页接口
useMethod() {
switch (this.method) {
case 'searchUserListByPage'://用户列表
this.searchUserListByPage()
break
case 'getAdminListByPage'://管理列表
this.getAdminListByPage()
break
case 'getServiceOrderListByPage': //订单列表
this.getServiceOrderListByPage()
break
}
//利用 this[this.method]() 可以更换掉switch循环 推举这样利用
this.method从何而来呢?=》来自我们所须要分页功能的vue文件中,表示的是列表方法题外话:this.userMethod()与this.method是可以省略的,这个各位看官自己去创造吧。由于省略的话与本人爱崇的代码风格不一致,就没去掉了。补一句(当你这里的case越多你也会感到这个方案的魅力)还是利用 推举行法吧回到我们所须要分页的详细vue文件中:
在这里我们该当写些什么呢?
一、定义一个名为(method)的参数 规则如下
只管即便与我们的列表方法名称保持同等,增加可读性二、列表方法的参数获取
getParams() {
let startTime = ''
let endTime = ''
if (this.rangeTime && this.rangeTime.length > 0) {
startTime = this.rangeTime[0].valueOf() / 1000
endTime = (this.rangeTime[1].valueOf() + this.dayMs) / 1000
}
return {
keyword: this.keyword,
state: this.state,
page: this.PAGINATION.currentPage,
offset: this.PAGINATION.pageSize,
startTime: startTime,
endTime: endTime
}
},
async searchUserListByPage() {
this.loading = true
let res = await searchUserListByPage({ ...this.queryParams })
this.tableData = res.body.list
this.PAGINATION.total = res.body.total
this.loading = false
},
为何里面传参不是 let res = await searchUserListByPage({ ...this.getParams() })详细参考《详细步骤》中的 三 、和 四、页面初始化只须要在 created 阶段 调用 this.check()详细参考《详细步骤》中的 四、 和 五、Ïcreated() {
this.check()
},