[ vue ] quasar框架踩坑:在vue文件外导入路由,执行router.push('/')没有效果

问题描述:

   

1. 如图所示的项目结构目录, axios.js 文件负责拦截全局请求和回复,我在拦截回复的代码中写了:如果服务器回复了一个401错误,则执行Router.push('/'),但是该方法失效,并不会出现跳转

import Vue from 'vue'
import axios from 'axios'
import Router from '../router/index.js'
import Store from '../store'
< 略... >
axios.interceptors.response.use(function(response){
  return response
},function(error){
  switch (error.response.status){
      case 401:
          Vue.toasted.error('401:Authorization error')
          Store.dispatch('base/logout_action')
          let rt = Router() // router/index.js 提供工厂函数,这里需要实例化它才能用
          rt.push('/').catch(e=>{})
          break;
  }
  return Promise.reject(error)
})
Vue.prototype.$axios = axios 

2. 接下来看  router/index.js ,它从 router/routes.js 中导入具体的路由,这里省略不说。

import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './routes'
Vue.use(VueRouter)

/*
 * If not building with SSR mode, you can
 * directly export the Router instantiation;
 *
 * The function below can be async too; either use
 * async/await or return a Promise which resolves
 * with the Router instance.
 */

export default function(){
  const Router = new VueRouter({
    scrollBehavior: () => ({ x: 0, y: 0 }),
    routes,

    // Leave these as they are and change in quasar.conf.js instead!
    // quasar.conf.js -> build -> vueRouterMode
    // quasar.conf.js -> build -> publicPath
    mode: process.env.VUE_ROUTER_MODE,
    base: process.env.VUE_ROUTER_BASE
  })
  return Router
}

我们看到:quasar提供的默认路由方式是导出了一个函数,而不是我们真正实例化的Router。

这就导致我在每次在vue文件外面使用都要实例化一次该函数,得到的是一个新的路由,最终导致路由跳转失效。

解决方案:

注意问题描述2 中高亮部分,写着如果不是SSR模式,则直接导出Router实例,于是我们把工厂函数去掉即可。在vue文件之外就可以直接导入并且正常使用了

备注:

vuex的使用同理!!

原文地址:https://www.cnblogs.com/remly/p/12995936.html