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寫入接口請求回來的權限路由
1 const res = await get_menu_list(params) 2 //根據唯一值過濾動態路由權限數據 3 const addMenuList = res.map(i => i?.code).filter(Boolean) 4 asyncRouterMap.forEach(item => { 5 if(item.children) { 6 item.children = item.children.filter(cItem => addMenuList.indexOf(cItem.meta?.code) !== -1) 7 } 8 // Router4中,去掉了 router.addRoutes ,只能使用 addRoute單個添加 9 router.addRoute(item) 10 }) 11
寫到這里,動態路由添加就成功了,在點擊菜單跳轉之后一切正常,但是瀏覽器刷新一下,頁面就變成了空白。
此刻,需要在路由跳轉前判斷是否被添加成功
// 設置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() } })