Ruoyi 若依项目模板创建多级菜单加载失败问题处理以及路由懒加载失败时将组件更换为notfound

src/store/modules/route.js

/* 遍历后台传来的路由字符串,转换为组件对象 */
function filterAsyncRouter(asyncRouterMap, isRewrite = false/* 是否重写服务端数据结构 */) {
  return asyncRouterMap.filter(route => {
    if (isRewrite && route.children) {
      route.children = filterChildren(route.children)
    }
    if (route.component) {
      if (route.component === 'Layout') {
        route.component = Layout
      } else {
        route.component = loadView(route.component)
      }
    }
    if (route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children, isRewrite)
    }
    return true
  })
}
/* 递归扁平化路由结构 */
function filterChildren(childrenMap, parentRoute) {
  var children = []
  childrenMap.forEach((el, index) => {
    if (parentRoute) {
      el.path = parentRoute.path + '/' + el.path
    }
    if (el.children && el.children.length) {
      if (el.component === 'ParentView') {
        el.children.forEach(c => {
          c.path = el.path + '/' + c.path
          if (c.children && c.children.length) {
            children = children.concat(filterChildren(c.children, c))
            return
          }
          children.push(c)
        })
        return
      }
    }
    children = children.concat(el)
  })
  return children
}
/* 路由懒加载失败时,重置为notfound页面 */
export const loadView = (view) => { // 路由懒加载
  return (resolve) => {
    require([`@/views/${view}`], resolve, err => {
      require([`@/views/error/notfound`], resolve)
      console.log(err)
    })
  }
}
Logo

快速构建 Web 应用程序

更多推荐