【转载】Vue3动态添加路由及解决页面刷新空白问题

原文地址: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
——用于个人纪录

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值