vue.js动态路由实现方法

本文介绍在Vue.js中如何实现动态加载路由,特别是在使用ElementUI框架并参考花裤衩后台管理框架的情况下,解决从后端获取路由信息并在前端动态加载组件的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在使用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’页面动态加载出来,所以我们定义一个import_router.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前端获取动态路由的情况,一定会遇到这个问题,而这个问题在网上确没人解答,所以我把一些重点代码放上这里来了。

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值