【问题标题】:How to import all Vue components from a folder?如何从文件夹中导入所有 Vue 组件?
【发布时间】:2019-06-18 01:00:44
【问题描述】:

我正在尝试从文件夹中自动加载我所有的 vue 组件, 如果我不使用 vue "Async Components",这会正常工作。

一旦我尝试将异步组件与 import 一起使用。我收到此错误:

10:11-36 Critical dependency: the request of a dependency is an expression

我的代码加载了所有组件,这会产生这个错误:

const ComponentContext = require.context('./', true, /\.vue$/i);

ComponentContext.keys().forEach((componentFilePath) => {

    const componentName = componentFilePath.split('/').pop().split('.')[0];
    Vue.component(componentName, () => import(componentFilePath));

});

如何解决这个问题?还是有其他方法可以做到这一点?

【问题讨论】:

    标签: vue.js webpack vuejs2 vue-component


    【解决方案1】:

    我必须在此处将问题与答案合并以获得最终解决方案:

    const ComponentContext = require.context('./', true, /\.vue$/i, 'lazy');
    
    ComponentContext.keys().forEach((componentFilePath) => {
    
        const componentName = componentFilePath.split('/').pop().split('.')[0];
        Vue.component(componentName, () => ComponentContext(componentFilePath));
    
    });
    

    'lazy' 第三个参数添加到require.context()() => import() 更改为() => ComponentContext()

    我可以在开发工具窗格的“网络”选项卡中看到捆绑包,但当我导航到不呈现任何自动加载组件的页面时,我看不到这些捆绑包。

    因此,我有理由确定上述代码是自动加载和动态导入的。我还将确认在我的项目中,我正在使用:

    require.context('~/components/common', true, /\.vue$/i, 'lazy')
    

    请注意我在~/components/common./ 的不同之处。您的项目需求可能会有所不同。我的~/resources/js 的Webpack 别名,所以我的完整路径是./resources/js/components/common。上面的其余代码是一个算法,可以保持不变。

    【讨论】:

      【解决方案2】:

      好的,我需要在中添加“懒惰”:

      const ComponentContext = require.context('./', true, /\.vue$/i, 'lazy');
      

      然后:

      Vue.component(componentName, () => ComponentContext(componentFilePath));
      

      【讨论】:

      • 好的,这里无处可寻,花几个小时搜索,应该在文档中的任何地方提及。现在测试,谢谢。
      【解决方案3】:

      代替

      Vue.component(componentName, () => import(componentFilePath));
      

      试试

      Vue.component(componentName, ComponentContext(componentFilePath));
      

      或者

      Vue.component(componentName, ComponentContext(componentFilePath).default);
      

      不确定默认部分。

      【讨论】:

      • 这不再进行异步导入,这正是 OP 想要做的。
      猜你喜欢
      • 2019-08-25
      • 2019-07-23
      • 2020-04-20
      • 2020-10-04
      • 2017-04-26
      • 1970-01-01
      • 1970-01-01
      • 2019-06-25
      • 1970-01-01
      相关资源
      最近更新 更多