Use Vue Router In Script

前端 未结 3 472
心在旅途
心在旅途 2021-01-29 10:17

I have a script that will redirect a user to the login screen when they get a response code of 401 - which means their session has expired within the API.

import         


        
3条回答
  •  一个人的身影
    2021-01-29 10:55

    This problem is is applicable to other frameworks like React and Angular and should be solved similarly there.

    Router instance is unavailable outside component hierarchy, it cannot be accessed when Axios interceptor is defined in module scope.

    It's also unwise to modify global Axios instance because it can be used by third-party libraries and cause unexpected side effects for them, this also makes clean-up more complicated in tests.

    Local Axios instance can be defined in Vue application, also allows to define specific options like base URL:

    Object.defineProperty(Vue.prototype, 'axios', {
      get() {
        return this.$root._axiosInstance;
      }
    });
    
    Vue.mixin({
      created() {
        if (this.$root === this) {
          let axiosInstance = axios.create({/*...*/});
          axiosInstance.interceptors.response.use(
            response => response,
            error => {
              ...
              this.$router.push(...);
              ...
            }
          );
    
          this._axiosInstance = axiosInstance;
        }
      }
    });
    

    And is accessed as this.axios inside components.

提交回复
热议问题