vite 使用import.meta.glob动态添加vue页面

使用vite的 GlobImport 动态导入多个vue页面

在使用vite实现后台管理系统的时候,有个需求是动态导入views文件夹下面的所有页面,vite提供了一个Glob Import方法。

如果直接使用import.meta.glob,vscode会报类型ImportMeta上不存在属性“glob”的错误,需要在tsconfig文件下添加类型定义vite/client

{
  "compilerOptions": {
    "types": ["vite/client"]
  }
}

之前的代码

export function filterAsyncRoutes(routes, roles) {
  const res = []
  routes.forEach(route => {
    const tmp = {...route}
    //if (hasPermission(roles, tmp)) {
      const component = tmp.component
      if (route.component) {
        if (component == 'Layout') {
          tmp.component = Layout
        } else {
          tmp.component = (resolve) => require([`@/views/${component}`], resolve)
        }
        if (tmp.children) {
          tmp.children = filterAsyncRoutes(tmp.children, roles)
        }
      }
      res.push(tmp)
    //}
  })
  return res
}

使用import.meta.glob 改写代码,动态添加

const modules = import.meta.glob('../../views/**/**.vue');
export const filterAsyncRoutes = (
  routes: RouteRecordRaw[],
  roles: string[]
) => {
  const res: RouteRecordRaw[] = [];
  routes.forEach(route => {
    const tmp = { ...route } as any;
    // if (hasPermission(roles, tmp)) { // 目前没有给菜单设置权限,所以暂时去掉
    if (tmp.component == 'Layout') {
      tmp.component = Layout;
    } else {
      const component = modules[`../../views/${tmp.component}.vue`] as any;
      if (component) {
        tmp.component = modules[`../../views/${tmp.component}.vue`];
      } else {
        tmp.component = modules[`../../views/error-page/404.vue`];
      }
    }
    res.push(tmp);

    if (tmp.children) {
      tmp.children = filterAsyncRoutes(tmp.children, roles);
    }
    // }
  });
  return res;
};
  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值