[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'
< 略... >
sponse.use(function(response){
return response
},function(error){
switch (sponse.status){
case 401:
<('401:Authorization error')
Store.dispatch('base/logout_action')
let rt = Router() // router/index.js 提供⼯⼚函数,这⾥需要实例化它才能⽤
rt.push('/').catch(e=>{})
react router拦截
break;
}
ject(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 f.js instead!
// f.js -> build -> vueRouterMode
// f.js -> build -> publicPath
mode: v.VUE_ROUTER_MODE,
base: v.VUE_ROUTER_BASE
})
return Router
}
我们看到:quasar提供的默认路由⽅式是导出了⼀个函数,⽽不是我们真正实例化的Router。
这就导致我在每次在vue⽂件外⾯使⽤都要实例化⼀次该函数,得到的是⼀个新的路由,最终导致路由跳转失效。
解决⽅案:
注意问题描述2 中⾼亮部分,写着如果不是SSR模式,则直接导出Router实例,于是我们把⼯⼚函数去掉即可。在vue⽂件之外就可以直接导⼊并且正常使⽤了
备注:
vuex的使⽤同理!!