hidar
hidar

Reputation: 5939

How to import/use translation files based on locale

So, I have a list of countries in three different languages as:

countries-fr.js
countries-en.js
countries-de.js

I would like to require these files inside my component only based on the language selected.

Currently I am doing:

<template>
...
<p v-for="country in countryList"> {{ country.name }} </p>
...
</template>

<script>
import {EN} from '../../countries-en.js'
import {DE} from '../../countries-de.js'
import {FR} from '../../countries-fr.js'

export default {
  data () {
   EN, FR, DE
  },

  computed:  {
    countryList () {
      let lang = this.$store.state.user.lang

      if(lang == "EN"){return this.EN},
      if(lang == "FR"){return this.FR},
      if(lang == "DE"){return this.DE},
    }
  }
}

This works obviously but I don't like I have to import the three files beforehand, and If I add 100 languages, then I will have to do that.

So, my question is: how do I import a file based on the current locale?

I could do if/else before the <script> and import but that doesn't seem the ideal way to import it.

Upvotes: 0

Views: 2124

Answers (1)

ProblemsOfSumit
ProblemsOfSumit

Reputation: 21325

You can use async and dynamic imports if you use webpack / the standard vue-cli build. This article can help you out on that: https://medium.com/@michalozogan/how-to-split-moment-js-locales-to-chunks-with-webpack-de9e25caccea

It's basically

const content = () => import(`../../countries-${locale}.js`)

You could also use fetch() after the location was figured out if you don't have to bundle the files. So let's say you define the locale in a router navigation guard. Then, fetch the content and use it. Obviously for it to be fetched it needs to be hosted somewhere so you'd have to upload it yourself (or use a service like contentful).

Upvotes: 1

Related Questions