隐菌子 2022-05-23 22:09 采纳率: 58.3%
浏览 2075
已结题

vite中import.meta.glob动态路由的疑问

最近通过博客学习了import.meta.glob 函数从文件系统导入多个模块:
//匹配到的文件默认是懒加载的

const modules = import.meta.glob('./dir/*.js')
以上将会被转译为下面的样子:
// vite 生成的代码
const modules = {
  './dir/foo.js': () => import('./dir/foo.js'),
  './dir/bar.js': () => import('./dir/bar.js')
}

当用其来进行路由引入的时候,由于需要在文件中进行判断是否注册为路由组件,所以在通过.then获得相应模块

//组件中
export default defineComponent({
  name: 'home',
  isRouter: true,//注册为路由
  setup() {
  }
})

//方法中
 const modules = import.meta.glob('../views/**/*.vue')
   for (const path in modules) {
    modules[path]().then((mod) => {
      const file = mod.default;
      if (!file.isRouter) return //判断
      router.addRoute({
        path: `/${file.name}`,
        name: `${file.name}`,
        component: file //then方法访问到的模块
      })
    })
  }

当通过遍历 modules 对象的 key并且.then后访问到了模块,后再用获取到的模块直接注册路由,这样会不会丧失路由的懒加载效果?
我一直在纠结如果不使用.then的话直接component:modules[key],就可以保留原始的路由懒加载格式,即component:()=>import('路径'),但使用.then后就直接变为了component:组件模块`(>﹏<)′

  • 写回答

3条回答 默认 最新

  • 关注

    img

    img


    不会 在main.js全局配置 ,点击是触发(路径)才会请求数据--->

    评论

报告相同问题?

问题事件

  • 系统已结题 5月31日
  • 赞助了问题酬金10元 5月25日
  • 创建了问题 5月23日