vue后台登录系统切换用户时,如何避免路由混淆?(重置路由)
问题:目前路由大多都是后端动态传过来的,不同用户菜单权限会有所不同,在切换用户时,会出现菜单错乱的情况,这时候就需要重置菜单了
1.利用刷新网页
点击退出切换账号的时候,清除token并刷新页面
- 采用
window.reload(),或者router.go(0)刷新时,整个浏览器进行了重新加载,闪烁,体验不好 - 运用
this.$forceUpdate()强制刷新 - 通过调用全局的 location.refresh 方法来实现应用
刷新来实现前端路由的重置。
2.初始化路由
1.对路由重新赋值
this.$router.replace({path: '/login'}); // 对路由进行重新赋值
location.reload(); // 刷新页面双重保证
2.通过替换当前 vue-router 的 matcher 属性对象来实现在不刷新页面的情况下重置当前路由实例。
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
// 解决ElementUI导航栏中的vue-router在3.0版本以上重复点菜单报错问题
const originalPush = Router.prototype.push
Router.prototype.push = function push(location) {
return originalPush.call(this, location).catch(err => err)
}
export let routes = [{
path: '/login',
name: 'login',
omponent: () => import('@/views/login/login'),
}
]
const createRouter = () => new Router({
routes: routes
})
const router = createRouter()
//写一个重置路由的方法,切换用户后,或者退出时清除动态加载的路由
export function resetRouter() {
const newRouter = createRouter()
router.matcher = newRouter.matcher // 新路由实例matcer,赋值给旧路由实例的matcher,(相当于replaceRouter)
}
export default router
matcher 是什么
在源码的 src/index.js 入口文件中的
VueRouter类的构造函数中可见,路由实例的matcher对象由create-matcher中的内部方法 createMatcher 创建 而来。
// ... other code
import { createMatcher } from './create-matcher'
// ... other code
export default class VueRouter {
// ...
constructor(options: RouterOptions = {}) {
// ...
this.matcher = createMatcher(options.routes || [], this)
let mode = options.mode || 'hash'
// ... other code
}
// ... other code
addRoutes(routes: Array<RouteConfig>) {
this.matcher.addRoutes(routes)
if (this.history.current !== START) {
this.history.transitionTo(this.history.getCurrentLocation())
}
}
}