像以前传统的路由配置,会导致有些页面当前用户是访问不到的,但是我把路由添加到了路由表router.js中,导致我可以在地址栏中手动输入路由而访问到当前用户访问不到的页面进行越权访问。现在我将必须的页面路由添加到路由表里面,其他的页面路由根据后台返回的数据自动的进行生成,通过cookie判断当前用户是否登录,如果未登录则到login页面,已登录则获取到当前的权限树菜单。
router.js
//一直存在的路由
const commonRoutes = [
{
path: '/login',
name: 'login',
component: () => import('views/login')
}
]
// 需要通过后台数据来生成的路由配置
export const asyncRoutes = {
// 内容管理
'dataDirectory': {
path: 'dataDirectory',
name: 'dataDirectory',
component: () => import('views/contentManagement/dataDirectory')
},
'dataTopic': {
path: 'dataTopic',
name: 'dataTopic',
component: () => import('views/contentManagement/dataTopic')
}
}
export const createRouter = () => {
return [...commonRoutes]
}
const routes = createRouter()
export default routes
在until中去动态生成路由配置
// 初始化路由
const initRouters = (menus) => {
let routers = [{
path: '/',
redirect: '',
name: 'portal',
component: () => import('portal'),
children: []
}]
let flag = false
console.log(menus)
menus.forEach((item, index) => { // eslint-disable-line
if (item.children.length === 0) {
routers.push(asyncRoutes[item.name])
console.log(routers)
} else {
if (!flag) {
routers[0].redirect = item.children[0].ename
flag = true
console.log(routers)
}
for (let child of item.children) {
routers[0].children.push(asyncRoutes[child.ename])
}
console.log(routers)
}
})
//添加一些特殊页面
routers = routers.concat([
// 异常页面跳转
{
path: '/404',
name: 'notFound',
component: () => import('views/errors/Not_found')
},
{
path: '/500',
name: 'serverError',
component: () => import('views/errors/Server_error')
},
{
path: '*',
redirect: {path: '/404'}
}
])
router.$addRoutes(routers)
}
// 根据cookie判断是否登录
export const isLogin = () => {
let cookie = Cookie.getCookie('sid')
if (!cookie) {
return false
} else {
return true
}
}
//先判断是否登录,如果登录成功判断当前url地址栏中的数据是否存在,不存在则跳转登录页。
let hasMenus = false
router.beforeEach((to, from, next) => {
if (isLogin()) {
if (to.path === '/login') {
next({path: '/'})
} else {
if (hasMenus) {
next()
} else {
new Promise((resolve, reject) => {
getMenuTreeList(resolve, reject)
}).then(res => {
hasMenus = res
next({path: to.path || '/'})
}).catch(() => {})
}
}
next()
} else {
hasMenus = false
if (to.path === '/login') {
next()
} else {
next('/login')
}
}
})