Vue3动态添加路由及解决页面刷新空白问题
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() } })