从子文件夹动态导入Vue

时间:2019-01-31 17:24:22

标签: javascript vue.js

我正在尝试将某个子文件夹中的所有.vue文件导入另一个组件。我知道Global registration of Base components,但这似乎无济于事。

假设我有默认的Vue组件(不是主要组件),内容如下:

export default {
  components: {
    red: () => import('./panes/red'),
  },
  data() {
    return {
      current: false,
    };
  },

我的文件结构是这样的:

/src
- main.js
- main.vue
-- components/
-- panes/
--- /red.vue
--- /green.vue
--- /blue.vue
-- SubMain.vue

我正在尝试为components文件夹动态创建SubMain.vue对象。

所以我在SubMain.vue中尝试这样的事情:

  import myComponents from './src/components/panes';

  ...

  components: Object.keys(myComponents).reduce((obj, name) => {
    return Object.assign(obj, { [name]: () => import(myComponents[name]) })
  }, {}),

但是eslint给我有关Missing file extension变量的Unable to resolve path to modulemyComponents的错误。是的,我仔细检查了路径并尝试了其他路径。没有。我正在使用Vue CLI 3项目。

2 个答案:

答案 0 :(得分:1)

我认为,没有索引文件可以为您聚合组件的导入/导出,您不能以这种方式导入多个组件。参见Import multiple components in vue using ES6 syntax doesn't work

答案 1 :(得分:1)

如果您使用的是Webpack,则可以使用require.context

import _kebabCase from lodash/kebabCase

const components = require.context('src/panes', true)

components.keys().map(component => {
    // turn './ComponentName.vue' into 'component-name'
    const componentName = _kebabCase(
        component.replace(/^\.\//, '').replace(/\.vue$/, '')
    )
    // register new component globally
    Vue.component(componentName, components(component))
})