简体   繁体   中英

Vue.js dynamic imports

Vue.js fellow developers,

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 ).

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 .

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`; ).

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. 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.

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? If those lang files have js functions in there, aside from data, then maybe its better to implement it as a factory function.

But if its just pure data, why not json? Or if it really needs to be on js, why not just attach it globally or have it on 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.

You can alway check the current VUE_APP_LANG set on your .env using

process.env(VUE_APP_LANG)

尝试这个:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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