在脚本中使用 Vue 路由器

Posted

技术标签:

【中文标题】在脚本中使用 Vue 路由器【英文标题】:Use Vue Router In Script 【发布时间】: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) 【参考方案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 访问。

【讨论】:

以上是关于在脚本中使用 Vue 路由器的主要内容,如果未能解决你的问题,请参考以下文章

Vue路由器更改页面时如何加载Jquery插件/脚本?

Vue Router - 路由加载后调用函数

(Nuxt.js/Vue.js) - 脚本只运行一次,更改路由/刷新页面后停止运行

vue3 路由器不显示我的组件

vue同级路由 怎么调用另外一个页面的函数

Vue.js 将 javascript 文件路由为索引页面