如何使用动态名称导出变量

我在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"


qq_笑_17
浏览 284回答 3
3回答

慕桂英4014372

您可以通过这种方式进行操作,检查是否需要什么。创建一个文件以导入组件的组合:allComponents.jsexport 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();

慕村225694

我创建了一个库进行这种类型的导出,任何想要的人都可以通过安装 npm我创建了一个Webpack插件,该插件可以从组件进行命名导出,也许这可以帮助其他人Weback插件-named-exports
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript