项目需求:根据后台返回动态加载路由表
实现方案:
- 在login.vue登录时,获取菜单权限,并存储在localstorage
getMenuByUserId(userId){
loginService.getMenuByUserId({userId:userId}).then(res=>{
if(!res.success){
this.$message.error("菜单查询失败!")
return
}
this.set_promission_menu(res.result)
setStorage("routerData",res.result) //存储routerData
this.$router.push('/page')
})
}
- 在router.js中配置:
1)配置默认的静态路由
const router = new Router({
routes: [{
path: '/login',
name: 'login',
component: login,
meta: {
requiresAuth: true
}
},
{
path: '/',
redirect: '/login',
name: 'loginRid',
component: login,
meta: {
requiresAuth: true
}
}
]
})
2)配置路由监听
router.beforeResolve((to, from, next) => {
let isLogin = getStorageByKey("isLogin")
let isLoaded = false
if (to.matched.length === 0) {
//动态加载路由
addDynamicRoutes()
isLoaded = true
next({ ...to, replace: true })
} else {
next()
}
if (to.path == '/login') { //如果是登录页面路径,就直接next()
next();
} else {
if (isLogin) {
if (!isLoaded) {
//动态加载菜单
addDynamicRoutes()
}
next()
} else {
next('/login');
}
}
})
填坑记录:
- 控制台出现死循环:
addDynamicRoutes方法中写入router.push({path:"*",name:“404“})导致死循环,是因为push会重新走beforeEach方法导致。
PS:next(”/path"):会重新走入beforeEach。next()会重新跳转 - 登陆后页面出现空白页,在当前tab页重新登录,就会进入页面。发现时to.match为空导致的,判断可能因为时router异步加载为空的原因,如果为空,则重新加载路由
if (to.matched.length === 0) {
//动态加载路由
addDynamicRoutes()
isLoaded = true
next({ ...to, replace: true })
} else {
next()
}
- 浏览器刷新时,页面为空,也是to.match为空,判断应该时因为刷新时vue初始化,router初始化,需要重新加载路由,方法同2
- 使用elementui做侧边栏时,获取$router.option.routes为空,判断是因为addRoutes没有更新,在addRoutes前强制更新
router.options.routes.push({
path: '/page',
name: 'page',
component: pageBox,
children: childTree,
meta: {
requiresAuth: true
}
})