原文地址:https://www.cnblogs.com/liuzichen/p/15766929.html
——用于个人纪录
1、route/index.ts 写入静态路由及动态路由
// 静态路由
export const constantRouterMap = [
{
path: '/',
redirect: '/home/index',
},
{
path: '/home',
component: component,
meta: { title: '首页',},
redirect: '/home/index',
children: [
{
path: 'index',
name: 'HomeIndex',
component: () => import('../views/home/index.vue'),
meta: { title: '首页', keepAlive: true }
},
]
},
]
// 动态路由
export const asyncRouterMap = [
{
path: '/xxx',
component: component,
meta: { title: 'xxx' },
redirect: '/xxx',
children: []
},
...
]
const router = createRouter({
history: createWebHashHistory()
routes: constantRouterMap // 只写静态路由
})
2、store/index.ts写入接口请求回来的权限路由
const res = await get_menu_list(params)
//根据唯一值过滤动态路由权限数据
const addMenuList = res.map(i => i?.code).filter(Boolean)
asyncRouterMap.forEach(item => {
if(item.children) {
item.children = item.children.filter(cItem => addMenuList.indexOf(cItem.meta?.code) !== -1)
}
// Router4中,去掉了 router.addRoutes ,只能使用 addRoute单个添加
router.addRoute(item)
})
写到这里,动态路由添加就成功了,在点击菜单跳转之后一切正常,但是浏览器刷新一下,页面就变成了空白。
此刻,需要在路由跳转前判断是否被添加成功
// 设置flag,防止非权限路由,页面死循环重定向
let flag = 0
router.beforeEach((to, from, next) => {
if (flag === 0 && to.matched.length == 0) {
flag++
router.push(to.path);
} else if (flag !== 0 && to.matched.length == 0) {
next('/')
} else {
next()
}
})
原文地址:https://www.cnblogs.com/liuzichen/p/15766929.html
——用于个人纪录