Axios拦截器中的Vue-Router

时间:2018-10-23 11:45:22

标签: vue.js vuejs2 axios vue-router

我用vue-cli 3创建一个项目,所以我运行:

>vue create my-app;
>cd my-app
>vue add axios

vue使用以下代码在my-app \ src \ plugins \文件中创建axios.js:

"use strict";

import Vue from 'vue';
import axios from "axios";

// Full config:  https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

let config = {
  // baseURL: process.env.baseURL || process.env.apiUrl || ""
  // timeout: 60 * 1000, // Timeout
  // withCredentials: true, // Check cross-site Access-Control
};

const _axios = axios.create(config);

_axios.interceptors.request.use(
  function(config) {
    // Do something before request is sent
    return config;
  },
  function(error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

// Add a response interceptor
_axios.interceptors.response.use(
  function(response) {
    // Do something with response data
    return response;
  },
  function(error) {
    // Do something with response error
    return Promise.reject(error);
  }
);

Plugin.install = function(Vue, options) {
  Vue.axios = _axios;
  window.axios = _axios;
  Object.defineProperties(Vue.prototype, {
    axios: {
      get() {
        return _axios;
      }
    },
    $axios: {
      get() {
        return _axios;
      }
    },
  });
};

Vue.use(Plugin)

export default Plugin;

但是我需要在响应拦截器中访问vue-router,我已经尝试从'vue-router'添加导入Router;并使用Roter.push(),但是在执行时说push不是方法。我也不能使用This或Vue。$ router ..

我该如何解决? tks

1 个答案:

答案 0 :(得分:1)

为了在axios拦截器内部或组件文件外部的几乎任何位置使用路由器,我们必须导入应用程序的路由器实例,该实例是在路由器入口文件(默认为router.js)中创建的。

实例应从同一路径导入,就像在应用程序的入口文件中完成的一样(默认为main.js):

import router from './router'

以这种方式可以访问所有方法,如documentation

中所述
相关问题