vue.js动态路由实现方法

在使用vue.js做管理后台的时候,路由不是写死在前端的,而是用户登录后,通过接口动态去后台获取的,这里就产生了如果将动态获取的路由加载进来的问题。

我使用的是UI框架是ElementUI,参考了花裤衩封装的后台管理框架,所以我不会贴上所有代码,仅仅是部分吧,这里的难度是这样:接口获取的数据中,component是一段字符串,例如下面代码所示:

{
        path: '/page',
        name: 'Page',
        component: 'Layout',
        redirect: 'noredirect',
        meta: {
          title: '页面模板',
          icon: 'guide'
        },
        children: [{
            path: 'dashboard',
            name: 'PageDashboard',
            meta: {
              title: '仪表盘页'
            },
            component: 'template/dashboard/index'
          }
          }
        ]
      }

前端要将’template/dashboard/index’页面动态加载出来,所以我们定义一个js:import_component.js

module.exports = file => () => import('@/views/' + file + '.vue')

在使用的地方(更加框架,是在permission.js使用)引入:

const importRouter = require('@/router/import_router')

function filterAsyncRouter(asyncRouterMap) {
  const accessedRouters = asyncRouterMap.filter(route => {
    if (route.component) {
      if (route.component === 'Layout') {
        route.component = Layout
      } else {
        route.component = importRouter(route.component)
      }
    }
    if (route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children)
    }
    return true
  })
  return accessedRouters
}

这里不再多做解释了,如果各位在工作中遇到了要vue.js前端获取动态路由的情况,一定会遇到这个问题,而这个问题在网上确没人解答,所以我把一些重点代码放上这里来了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章