如何知道axios请求结束,可以在请求结束的时候设置loading或者别的操作?

新手上路,请多包涵

项目是vue2+elementui

最近有一个问题,以前的项目是在response的返回值里面包含code,msg,data,需要判断code==200后在赋值data数据,可以在

this.$ajax.getTableData(id).then(res => {
    if(res.code == 200){ 
        关闭loading或者进行一些调用完成的操作
    }
}

现在改成了使用http码来判断,axios使用拦截器做了拦截,但是直接res就是数据,不知道loading该写在哪,有些请求完成的操作也不知道该写在哪里。。,
求指教

service.interceptors.response.use( response => {
    const code = response.status
    if(code == 200) {
        const res = response.data
        return res
    }else {
        Message({
            message: response.data.error || '失败',
            type: 'error',
            duration: 20000
        })
        return Promise.reject(new Error(response.data.error))
    }
}
 error => {
   if(error.response.status == 400){
    ....
   }
 }
)

页面调用写的api

this.$ajax.getTableData(id).then(res => { this.data = res.list})
阅读 1.8k
2 个回答

先简单的回复一下,你看看

showLoading();
try {
    const res = await this.$ajax.getTableData(id);
    this.data = res.list;
// } catch { // 没得错误处理,所以不需要 catch 了
} finally {
    hideLoading();
}

如果你的环境有 Promise.prototype.finally,可以

showLoading();
this.$ajax.getTableData(id)
    .then(res => { this.data = res.list})
    .finally(() => hideLoading());

如果是全局的loading可以写在拦截器里。
如果是局部的,可以用 .finally() 去处理

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题