在脚本中使用 Vue Router [英] Use Vue Router In Script

查看:64
本文介绍了在脚本中使用 Vue Router的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个脚本,当用户收到 401 响应代码时,它会将用户重定向到登录屏幕 - 这意味着他们的会话已在 API 中过期.

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)
})

我希望使用 vue 路由器而不是 window.location 重定向到登录页面.

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' })

出现错误.

在这种情况下如何使用 vue 路由器?

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

推荐答案

这个问题适用于其他框架,如 React 和 Angular,应该类似解决.

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

Router 实例在组件层次结构之外不可用,当 Axios 拦截器定义在模块范围内时无法访问它.

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

修改全局 Axios 实例也是不明智的,因为它可以被第三方库使用,并且会给它们带来意想不到的副作用,这也使得测试中的清理变得更加复杂.

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.

本地 Axios 实例可以在 Vue 应用程序中定义,也允许定义特定选项,如基本 URL:

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;
    }
  }
});

并且在组件内部作为 this.axios 访问.

And is accessed as this.axios inside components.

这篇关于在脚本中使用 Vue Router的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆