若依动态路由

文章讲述了如何在Vue.js应用中动态添加路由,包括从后端获取路由数据,处理数据以添加component属性,以及将树形结构的路由转换为一维数组,以便于渲染页面。主要涉及过滤、转换和添加路由的函数实现。
摘要由CSDN通过智能技术生成

动态添加路由

// 这是现有的公共路由
export const constantRoutes = [
  {
    path: '/redirect',
    component: Layout,
    hidden: true,
    children: [
      {
        path: '/redirect/:path(.*)',
        component: () => import('@/views/redirect/index.vue')
      }
    ]
  },
  {
    path: '/login',
    component: () => import('@/views/login'),
    hidden: true
  },
  {
    path: '/register',
    component: () => import('@/views/register'),
    hidden: true
  },
  {
    path: "/:pathMatch(.*)*",
    component: () => import('@/views/error/404'),
    hidden: true
  },
  {
    path: '/401',
    component: () => import('@/views/error/401'),
    hidden: true
  },
  {
    path: '',
    component: Layout,
    redirect: '/index',
    children: [
      {
        path: '/index',
        component: () => import('@/views/index'),
        name: 'Index',
        meta: { title: '首页', icon: 'dashboard', affix: true }
      }
    ]
  },
  {
    path: '/workbench',
    component: Layout,
    name: 'Workbench',
    hidden: true,
    meta: { title: '工作台', icon: 'dashboard' }
  },
  {
    path: '/user',
    component: Layout,
    hidden: true,
    // redirect: 'noredirect',
    children: [
      {
        path: 'profile',
        component: () => import('@/views/system/user/profile/index'),
        name: 'Profile',
        meta: { title: '个人中心', icon: 'user' }
      }
    ]
  }
]

从后端去请求路由字符串,然后处理传回来的数据

//从后端请求路由字符串,进行处理
generateRoutes(roles) {
        return new Promise(resolve => {
          // 向后端请求路由数据
          getRouters().then(res => {
            const sdata = JSON.parse(JSON.stringify(res.data))
            const rdata = JSON.parse(JSON.stringify(res.data))
            const defaultData = JSON.parse(JSON.stringify(res.data))
            const sidebarRoutes = filterAsyncRouter(sdata)
            const rewriteRoutes = filterAsyncRouter(rdata, false, true)
            const defaultRoutes = filterAsyncRouter(defaultData)
            const asyncRoutes = filterDynamicRoutes(dynamicRoutes)
            const simpleRoutes = setSimpleRouters(defaultRoutes)
            console.log(simpleRoutes,"一维数组");
            asyncRoutes.forEach(route => { router.addRoute(route) })
            this.setRoutes(rewriteRoutes)
            this.setSidebarRouters(constantRoutes.concat(sidebarRoutes), simpleRoutes)
            this.setDefaultRoutes(sidebarRoutes)
            this.setTopbarRoutes(defaultRoutes)
            constantRoutes.concat(sidebarRoutes).forEach(route => {
              if (!isHttp(route.path)) {
                router.addRoute(route) // 动态添加可访问路由表
              }
            })
            resolve(rewriteRoutes)
          })
        })
      },

处理函数是这个,将每个路由以及他的子路由children都加上一个component:组件,

      //处理的函数是这个
      // 遍历后台传来的路由字符串,转换为组件对象
function filterAsyncRouter(asyncRouterMap, lastRouter = false, type = false) {
  return asyncRouterMap.filter(route => {
    if (type && route.children) {
      route.children = filterChildren(route.children)
    }
    if (route.component) {
      // Layout ParentView 组件特殊处理
      if (route.component === 'Layout') {
        route.component = Layout
      } else if (route.component === 'ParentView') {
        route.component = ParentView
      } else if (route.component === 'InnerLink') {
        route.component = InnerLink
      } else {
        route.component = loadView(route.component)
      }
    }

    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children, route, type)
      delete route['redirect']
    } else {
      delete route['children']
      delete route['redirect']
    }
    return true
  })
}

然后在代码块2里面的动态添加路由部分,加后端返回的添加到路由里去
在这里插入图片描述

还有一部分,将上面处理完的数据,也就是树形结构的数据,转换成一维数组的结构,因为后面,不管在component:layout,还是component:ParentView,都需要去一维数组中找到当前页面路径相同的数据,通过这条数据下的children去渲染app-item,如下图,每一例都是app-item
在这里插入图片描述
转换为一维数组的代码如下,一直递归无穷级

function setSimpleRouters(allRoutes) {
  let _simpleArr = []
  return setWqRouters(allRoutes,'',_simpleArr)
}
function setWqRouters(allRoutes,firstLevel,_simpleArr){
  allRoutes.forEach(r => {
    const fatherLevel = firstLevel+ (r.path.includes('/')? r.path : '/'+r.path)
    _simpleArr.push({...r, path: fatherLevel})
    if(r.children && Array.isArray(r.children)){
      r.children.forEach(s => {
        const childLevel = fatherLevel+(s.path.includes('/')? s.path : '/'+s.path)
        _simpleArr.push({...s,path: childLevel })
        // 递归路由
        if(s.children && Array.isArray(s.children))
        setWqRouters(s.children,childLevel,_simpleArr)
      })
    }
  })
  return _simpleArr
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值