为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

qq_笑_17 2021-05-03 10:29:40
我在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"
查看完整描述

3 回答

?
慕桂英4014372

TA贡献1871条经验 获得超13个赞

您可以通过这种方式进行操作,检查是否需要什么。


创建一个文件以导入组件的组合: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();


查看完整回答
反对 回复 2021-05-13
?
慕村225694

TA贡献1880条经验 获得超4个赞

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

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

Weback插件-named-exports


查看完整回答
反对 回复 2021-05-13
  • 3 回答
  • 0 关注
  • 283 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信