require.context 实现 “去中心化“ 管理

公司的电信大型项目,200多个路由,那么其中二级路由非常之多,我们首先会想到可以模块化封装子路由,然后循环引入children数组中,如下:

// 路由
{
   path: '/home',
   name: 'home',
   component: () =>import('@/views/home.vue'),
   children: []           // 这里放的是guest这个子路由
}

// 循环引入children中
function pushRouter(name, thisArray) {
    for (var i in routers) {
        if (routers[i].name == name) {
            for (var j in thisArray) {
                routers[i].children.push(thisArray[j]);
            }
        }
    }
}

// 客户登录 -- 引入模块路由添加进路由
import guest from './guest'
pushRouter('guest', guest);

// 这是guest.js文件下的内容 - 里面存放的是home的二级路由
const guest= [
  {
    path: "workbench", 
    name: 'workbench',
    title:'工作台',
    component: () => import(/* webpackChunkName: "about" */ '@/views/manage/package/workbench/index.vue')
  },
  {
    path: "asset", 
    name: 'asset',
    title:'资产数据类',
    component: () => import(/* webpackChunkName: "about" */ '@/views/manage/package/asset/index.vue')
  },
  {
    path: "customer", 
    name: 'customer',
    title:'客户数据类',
    component: () => import(/* webpackChunkName: "about" */ '@/views/manage/package/customer/index.vue')
  },
]

就像上面这样,把所有二级路由模块化封装,再通过循环引入,就可以很好的实现模块化,但是,我遇到了require.content,如果可以,我觉得一级路由都不用写了!直接上代码

{
    path: '/home',
    name: 'home',
    component: () => import('@/views/home/'),
    children: rootRouter(require.context('./home', true, /\.js$/)) 
    // 里面的./home是查找文件的路径,会筛出home文件夹中所有.js的文件,我这里home文件夹存放的是home的二级路由 
},

// require.context 去中心化管理
function rootRouter(ctx) {
  return (ctx.keys().map(key => ctx(key)))[0].default;
}

参考链接https://github.com/wuchangming/blog/blob/master/docs/webpack/require-context-usage.md.

参考链接
https://segmentfault.com/a/1190000038140401.

参考链接
https://segmentfault.com/a/1190000022329864.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值