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: []
},
...
]
route add 添加路由
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 => {
5if(item.children) {
6 item.children = item.children.filter(cItem => addMenuList.a?.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()
} })
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论