vue 后端返回路由 添加动态路由

参考链接:https://blog.csdn.net/qq_3190...

思路:
路由表不在前端进行比对,后台对用户的权限进行比对,返回给前端一个比对好的路由表,且返回的路由表

  {
    path: '/people',
    name: 'people',
    meta: {
      title: '人口管理',
      requireAuth: true
    },
    component: () => import('@/views/main/Main'),
    children: [{
      path: '/people-list',
      name: 'people-list',
      meta: {
        icon: 'el-icon-user-solid',
        title: '人口管理',
        requireAuth: true
      },
      component: () => import('@/views/people/list')
    }, {
      path: '/people-detail',
      name: 'people-detail',
      meta: {
        requireAuth: true,
        notCache: true,
        hideInMenu: true,
        title: route => `人口详情-${route.query.xm}`
      },
      component: () => import('@/views/people/detail')
    }]
  }
function filterRouter (routes) {
  const router = routes.map(route => {
    if (route.component === 'main') {
      route.component = _import('/main/Main')
    } else {
      route.component = _import(route.component)
    }
    if (route.meta.routeTitle) {
      route.meta.title = _title(route.meta.title, route.meta.routeTitle)
    }
    if (route.children && route.children.length > 0) {
      route.children = filterRouter(route.children)
    }
    return route
  })
  return router
}

这个函数的主要作用就是把后台传过来的字符串型的component转化为真正的组件
其中_import()函数的定义如下:

function _import (file) {
  return () => import('@/views' + file + '.vue')
}
function _title (title, routeTitle) {
  return route => `${title}${route.query[routeTitle]}`
}

使用router.onReady 调用一下获取的动态路由

router.onReady(() => generateRoutes())
function generateRoutes () {
  let vueMenus = localStorage.vueMenus
  if (vueMenus) {
    vueMenus = JSON.parse(vueMenus)
    const filterRoutes = filterRouter(vueMenus)
    // console.log('filterRoutes', filterRoutes)
    filterRoutes.map(item => {
      // console.log('item', item)
      router.addRoute(item)
    })
    router.addRoute({
      path: '*',
      meta: {
        hideInMenu: true
      },
      component: _import('/main/NotFound')
    })
    router.options.routes = router.options.routes.concat(filterRoutes)
    // console.log(router.options.routes)
  }
}

你可能感兴趣的:(vue 后端返回路由 添加动态路由)