【问题标题】:Dynamic Vue Import from a subfolder从子文件夹中导入动态 Vue
【发布时间】:2019-06-25 05:43:15
【问题描述】:

我正在尝试将某个子文件夹中的所有 .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

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

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

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

  ...

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

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

【问题讨论】:

  • panes 文件夹在哪里?
  • @BoussadjraBrahim 添加了它。它都在里面。

标签: javascript vue.js


【解决方案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))
})

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-23
      • 2019-08-25
      • 2019-08-03
      • 2013-03-25
      • 2019-01-25
      相关资源
      最近更新 更多