【Vue】axios interceptors 拦截配置

请问下我用interceptors拦截response的时候如何根据
response.data.statusCode == '-1'的时候调用iview组件给出提示,然后router跳转至登录页面呢?
回答
// 以下代码插入在响应拦截器返回数据时处理
let data = response.data;if(data.statusCode === -1){
    Vue.$Message.error('需要登录');
    setTimeout(function(){
        //  控制路由跳转或者直接改变href到登录页
        window.location.href = '/login' :
    },1000)
    return ;
}
return data;
以下代码是我前几天写的,也是用与ajax响应统一处理axios.interceptors.response.use(function (response) {
        if(response.data.code === 1){
            // 后端返回系统错误,抛出错误信息
            let ifr = document.getElementById("mainframe");
            if (ifr) {
                ifr.contentWindow.document.location.reload();
            } else {
                location.pathname === "/logout" ? location.href = '/' : location.reload();
            }
        }
        let url = response.config.url;
        // 自定义错误处理,此处错误不弹出提示,需要在传入的success回调中自定义对response code的处理,可能和具体业务逻辑有关,并不是所有非0的返回状态码都需要弹窗提示,依赖了loadsh.js
        let index = _.indexOf(["/query_login","/password_login","/user/get_wechat_bind_uuid","/user/query_login"],url);
        if(index >= 0){
            return response.data;
        }
        // 判断code
        let data = response.data;
        if(data.code !== 0){
            throw new Error(data.msg)
        }
        return response.data;
    }, function (error) {
        if(error){
            // 执行自定义错误回调
            return Promise.reject(error);
        }else{
            // 错误提示
            Vue.$Message.error(error.msg);
        }
    });
当在代码中使用 Vue.use(iView) 的时候,iView 会在 Vue 构造函数的原型上添加一个 $Message 属性,所以我们才可以在每个组件中使用 this.$Message.error() 方法( this 指向 Vue 组件实例),题主想要在一个单独的文件(非组件)中使用提示,只需直接从原型上拿到方法即可:
import Vue from 'vue'Vue.prototype.$Message.error('请先登录')
以上是 【Vue】axios interceptors 拦截配置 的全部内容, 来源链接: utcz.com/a/82504.html
