【问题标题】:How to Export Variables with a Dynamic Names如何导出具有动态名称的变量
【发布时间】:2019-09-15 08:42:09
【问题描述】:

我在 nuxt.js 中有一个 components 文件夹

/components/atoms/

在该文件夹中,我有一个 index.js 来动态导出所有组件

const req = require.context('./', true, /\.vue$/)

const components = {}

req.keys().forEach(fileName => {
  const componentName = fileName.replace(/^.+\/([^/]+)\.vue/, '$1')
  components[componentName] = req(fileName).default
})

export const { ButtonStyled, TextLead, InputSearch } = components

所以我可以随心所欲地完美导入

import { ButtonStyled } from "@/components/atoms"

问题是我正在定义要静态导出的变量,固定的,所以对于每个创建的组件,我需要手动添加另一个变量

我需要动态导出变量名

例子:

DynamicCreation = ['ButtonStyled', 'TextLead', 'InputSearch']

export const { DynamicCreation } = components 

// output -> export const { ButtonStyled, TextLead,InputSearch  } = components

我需要导出已经是非结构化变量的名称

注意:我不能使用这个export default components,因为我不能像这样导入import { ButtonStyled } from "@/components/atoms"

【问题讨论】:

    标签: javascript node.js vue.js nuxt.js atomic-design


    【解决方案1】:

    我创建了一个执行这种类型导出的库,任何想要的人都可以通过npm安装

    我创建了一个从组件进行命名导出的 Webpack 插件,也许这对其他人有帮助

    Weback Plugin - named-exports

    【讨论】:

      【解决方案2】:

      你可以这样做,看看是不是你需要的。

      创建一个文件以导入组件的组合:allComponents.js

      export default {
       componentOne: require('./passToOneComponent.js');
       componentTwo: require('./passToOneComponent.js');
       componentThree: require('./passToOneComponent.js');
      }
      

      在 index.js 中导出 allComponents.js 并使用您希望的名称:

      export {default as SomeName } from 'allComponents.js';
      

      所以在最终的文件中,你可以做这样的事情:

      import { SomeName } from 'index.js';
      
      SomeName.componentOne();
      

      【讨论】:

      • 正如我在问题描述中提到的,我需要动态导入,而不是静态导入
      【解决方案3】:

      你应该可以这样做:

      export default components
      

      然后在你想要使用组件的文件中:

      import * as components from '@/components/atoms'
      

      那么当你需要使用你的Vue文件中的组件时,你需要映射它们:

      @Component({
        components: {
          ButtonStyled: components.ButtonStyled
        }
      })
      

      现在你有:

      <ButtonStyled></ButtonStyled>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-01-12
        • 2012-12-14
        • 2017-09-04
        • 1970-01-01
        • 2017-06-03
        • 1970-01-01
        • 2013-05-29
        • 1970-01-01
        相关资源
        最近更新 更多