我项目中绝大部分请求接口处理数据的逻辑都很类似,如下所示:
async getList() {
try {
this.tableLoading = true
const res = await API_JOB.getJobList({
pageNum: this.pageNum,
pageSize: this.pageSize
})
if (res.code === 0) {
this.list = res.list || []
this.total = res.total
} else {
this.$message.error(res.msg)
}
} catch (error) {
console.error(error)
} finally {
this.tableLoading = false
}
}
请求接口的代码都是如此相似,
try catch、loading、response这些逻辑都是一样的,基于 DRY 原则,封装一个全局的请求接口的方法岂不美哉!
Vue.prototype.$fetch = function(api, loading = 'loading') {
return async (...args) => {
try {
this[loading] = true
const res = await api(...args)
if (res.code === 0) {
return res
} else {
this.$message.error(res.msg)
}
} catch (error) {
console.error(`[${api.name}]`, error)
} finally {
this[loading] = false
}
}
}
async getList() {
const res = await this.$fetch(API_JOB.getJobList, 'tableLoading')({
pageNum: this.pageNum,
pageSize: this.pageSize
})
if (res) {
this.list = res.list || []
this.total = res.total
}
}
相比原来,代码简洁了许多