【问题标题】:Use Vue Router In Script在脚本中使用 Vue 路由器
【发布时间】:2020-05-12 23:29:26
【问题描述】:

我有一个脚本,当用户收到 401 响应代码时,它会将用户重定向到登录屏幕 - 这意味着他们的会话在 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 来重定向到登录页面。

我已经尝试将这些代码行添加到脚本中:

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

我收到一个错误。

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

【问题讨论】:

  • 错误是什么?
  • TypeError: Cannot read property 'push' of undefined at eval (axios.js?dcce:26)

标签: vue.js nuxt.js


【解决方案1】:

确保您已经安装了 vue 路由器。如果还没有,这是安装方法

npm install vue-router // npm

或vue路由器cdn

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

与模块系统一起使用时,您必须通过 Vue.use() 显式安装路由器。做这个

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

Vue.use(VueRouter)

然后像这样重定向到其他页面

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

【讨论】:

    【解决方案2】:

    你可以试试这个:

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

    【讨论】:

    • TypeError: Cannot read property '$router' of undefined at eval (axios.js?dcce:25)
    【解决方案3】:

    这个问题适用于其他框架,如 React 和 Angular,应该在那里类似地解决。

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

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

    可以在 Vue 应用程序中定义本地 Axios 实例,也可以定义特定选项,例如基本 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 访问。

    【讨论】:

      猜你喜欢
      • 2017-04-10
      • 1970-01-01
      • 2019-11-04
      • 1970-01-01
      • 2023-02-09
      • 2021-02-08
      • 1970-01-01
      • 2021-02-26
      • 2018-03-23
      相关资源
      最近更新 更多