1.在路由守卫中 添加 需要判断 if(router.hasRoute(to))
router.beforeEach(async(to, from, next) => {
// 开启进度条
NProgress.start()
// 判断是否有token
const token = store.getters.token
if (token) {
// 判断是否去登录页
if (to.path === '/login') {
next('/')
// 关闭进度条
NProgress.done()
} else {
/**、8.、
去到所有页面之前都会走这里
先判断有没有用户信息
有,直接放行
没有,先获取到用户信息再放行
*/
// 获取用户信息
if (!store.getters.userId) {
// 获取用户的权限点
const { roles } = await store.dispatch('user/getUserInfo')
// 从动态路由数组中筛选出动态路由
const filterRoutes = asyncRoutes.filter(item => {
return roles.menus.includes(item.name)
})
store.commit('user/setRoutes', filterRoutes)
/**
问题1:addRoutes方法存在已知缺陷,官方给的解决方案是:重新再进一次 next(to.path)
问题2:{ path: '*', redirect: '/404', hidden: true } 必须放在路由规则数组的最后
*/
if(router.hasRoute(to)){
next()
}else {
router.addRoute
next(to)
}
} else {
next()
}
}
} else {
// 判断是否在白名单
if (whiteList.includes(to.path)) {
next()
} else {
next('/login')
// 关闭进度条
NProgress.done()
}
}
})
1.在路由守卫中 添加 需要判断 if(router.hasRoute(to))
router.beforeEach((to, from, next) => {
NProgress.start()
document.title = `${to.meta.title}`
const token = localStorage.getItem("oo")
let roles = ["common"]
if (!token && to.path !== '/login') {
next('/login')
} else {
if (router.hasRoute(to)) {//判断动态路由表的长度是否为0
next()
} else {
resRoute = handelRoutes(permissionRoutes[0].children, roles)
resRoute.forEach(route => {
router.addRoute(route)
})
router.addRoute({//向动态路由添加404页面
path: '/404',
name: '404',
component: () => import( /* webpackChunkName: "404" */ '../views/404.vue'),
meta: {
title: '路径错误'
}
})
router.addRoute({
// path: "*", // 这样用,vue3已经不支持,得下面的方式
path: "/:pathMath(.*)", // 此处需特别注意置于最底部
redirect: "/404"
})
// 如果 addRoute 并未完成,路由守卫会一层一层的执行执行,直到 addRoute 完成,找到对应的路由
next({
...to,
replace: true
})
}
}
第二种 在main.ts中进行路由添加 注意 要在app.use(router)前面