根据菜单动态添加路由

286 阅读1分钟

一个Bug,可以进入路由了 但是刷新后会404 image.png

image.png

因为 router.addRoute() 它们注册一个新的路由,也就是说,如果新增加的路由与当前位置相匹配,就需要你用 router.push() 或 router.replace() 来手动导航,才能显示该新路由。

解决方法,通过hasNewRoutes变量

// 动态添加路由的方法
export function addRoutes(menus){
  // 是否有新的路由
  let hasNewRoutes = false
  const findAndAddRoutesByMenus = (arr) =>{
      arr.forEach(e=>{
          let item = asyncRoutes.find(o=>o.path == e.frontpath)
          if(item && !router.hasRoute(item.path)){
              router.addRoute("admin",item)
              hasNewRoutes = true
          }
          if(e.child && e.child.length > 0){
              findAndAddRoutesByMenus(e.child)
          }
      })
  }

  findAndAddRoutesByMenus(menus)

  return hasNewRoutes
}

permission中这样改

   // 如果用户登录了 自动获取用户信息 并放在vuex中
    let hasNewRoutes = false
    if(token){
      let { menus } = await store.dispatch("actionGetInFo")
      // 这里动态添加路由
      hasNewRoutes = addRoutes(menus)
    }

    // 设置页面标题
    let title = (to.meta.title ? to.meta.title : "") + "--kennyouchou"
    document.title = title
    hasNewRoutes ? next(to.fullPath) : next()