将router分为两类创建
- 不受远程控制的路由
export const constantRoutes = [
{
path: '/404',
name: '404',
component: () =>
import ('@/views/404'),
hidden: true
},
]
-受远程控制的路由
export const asyncRoutes = [
{
path: '/home',
name: 'home',
component: () =>
import ('@/views/home'),
},
{
path: '/test',
name: 'test',
component: () =>
import ('@/views/test'),
},
]
const router = new Router({
routes: constantRoutes
})
// before 可不看,与动态router关系不大,
router.beforeEach(async(to, from, next) => {
// 这儿要用async 因为菜单的权限是要从接口获取的
next()
// 无论如何 next() 一定要有 不然router就不会渲染
// 当从定向时比如说, next({
// path: '/home'
// })
// 一定要在前面加上 if (to.path === '/login') { ...}之类的限制 不然会一直死循环 去到home页还会再去到home页
}
export default router
定义可显示的路由数组的nameList
const nameList = ['home',']
在vuex中对之前定义的asyncRoute进行筛选
import {
asyncRoutes,
constantRoutes
} from '@/router'
import router from '@/router';
const nameList = ['home']
const accessedRoutes = filterAsyncRoutes(asyncRoutes, nameList )
router.addRoutes([...accessedRoutes,
...constantRoutes
])
export function filterAsyncRoutes(routes, roles, metaObj) {
const res = []
routes.forEach(route => {
const tmp = {
...route
}
if (roles.includes(tem.name)) {
if (tmp.children) {
tmp.children = filterAsyncRoutes(tmp.children, roles, metaObj)
}
res.push(tmp)
}
})
return res
}
如果觉得这个不够清楚
可去往这儿
vue-router动态路由实现前端权限管理