Use Vue Router In Script

微笑、不失礼 提交于 2021-02-05 12:18:27

问题


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 axios from 'axios';

axios.interceptors.response.use(function (response) {
  return response;
}, function(error) {
  if(error.response.status === 401) {
    localStorage.clear();
    window.location = '/';
    return Promise.reject(error);
  }
  return Promise.reject(error)
})

I wish to use vue router instead of window.location to redirect to the login page.

I have tried adding these lines of code to the script:

import Vue from 'vue';
Vue.$router.push({ name: 'login' })

I get an error.

How would one go about using vue router in this instance?


回答1:


Make sure you already installed vue router. If not yet, this is how to install

npm install vue-router // npm

or vue router cdn

 <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>

When used with a module system, you must explicitly install the router via Vue.use(). Do this one

import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

then redirect to other page like this

this.$router.push({ name: 'nome-of-location'})



回答2:


You can try this:

this.$router.push({ name: 'nome-of-location'})



回答3:


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.



来源:https://stackoverflow.com/questions/59933678/use-vue-router-in-script

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!