简体   繁体   English

Vue.js 动态导入

[英]Vue.js dynamic imports

Vue.js fellow developers, Vue.js 开发人员,

I have a data set I'm storing in a .js file ( reason for using .js right now, is so I can preserve comments, etc ).我有一个数据集存储在 .js 文件中(现在使用 .js 的原因是为了保留注释等)。

My directory structure looks as such:我的目录结构如下所示:

├── data
│   ├── cards
│   │   ├── en.json
│   │   ├── fr.json

Somewhere in my app, I import that data and then declare it in my data.在我的应用程序的某个地方,我导入该数据,然后在我的数据中声明它。

import Cards from '@/data/cards/en.js';
data() {
  return {
    cards: Cards, // < Imported.
    ...
  }
}

What I'm trying to accomplish, is import that locale file based off of a language property set in my .env file VUE_APP_LANG=en .我想要完成的是根据我的 .env 文件VUE_APP_LANG=en设置的语言属性导入该语言环境文件。

What's the best way to go about this?解决这个问题的最佳方法是什么? Although I know it's not possible, it would be nice to import using string literals (eg import Cards from `@/data/cards/${curLang}.js`; ).虽然我知道这是不可能的,但使用字符串文字导入会很好(例如import Cards from `@/data/cards/${curLang}.js`; )。

I'm aware, that yes I can just group the two in a Cards.js file and have my array return an object, one for each locale but it's not as clean.我知道,是的,我可以将两者组合在Cards.js文件中,并让我的数组返回一个对象,每个区域设置一个,但它并不那么干净。 My preference is to keep locale data each in it's own dedicated file.我的偏好是将每个区域设置数据保存在自己的专用文件中。

Yes, I'm also aware of available plugins like vue-i18n , unfortunately it has shortcomings specific to my project needs.是的,我也知道像vue-i18n这样的可用插件,不幸的是它有一些特定于我的项目需求的缺点。

Thanks in advance!提前致谢!

You can actually use dynamic imports您实际上可以使用动态导入

import(`@/data/cards/${curLang}.js`).then(module => {
  // do something with the translations
});

Cant those lang files be json?那些 lang 文件不能是 json 吗? If those lang files have js functions in there, aside from data, then maybe its better to implement it as a factory function.如果那些 lang 文件中除了数据之外还有 js 函数,那么将它实现为工厂函数可能会更好。

But if its just pure data, why not json?但如果它只是纯数据,为什么不是 json 呢? Or if it really needs to be on js, why not just attach it globally or have it on vuex?或者如果它真的需要在 js 上,为什么不全局附加它或将它放在 vuex 上? So you dont need to import it.所以你不需要导入它。

And since you will be adding it to the current Vue component instance as data, probably just have it on vuex and add it as computed property.并且由于您将它作为数据添加到当前的 Vue 组件实例中,因此可能只需将它放在 vuex 上并将其添加为计算属性。

You can alway check the current VUE_APP_LANG set on your .env using您始终可以使用以下方法检查 .env 上设置的当前 VUE_APP_LANG

process.env(VUE_APP_LANG)

尝试这个:

const card = () => import "./Card"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM