vue.jsvue-i18nlanguage-translation

Vue: get translations from API


I use vue and I18n for translations. In hardcoded translations all works fine:

import { useI18n } from 'vue-i18n'
const { locale, t } = useI18n({ useScope: 'global' })

and from json file get value in template:

 <div >{{ t('headers.settings') }}</div>

const locale is equal to the lang user choose: 'en', 'fr' etc

For dynamic data I get an API endpoint. The structure looks like this:

 data: {
  "key": "Configuration",
  "name": {
   "en": "configuration",
   "nl": "configuratie",
   "fr": "configuration"
 },
  "description": {
   "en": "this is the configuration",
   "nl": "dit is de configuratie",
   "fr": "c'est la configuration"
 },

}

so to get name in english it's :

<div> {{ data.name.en }} </div>

Question: I don't quite understand how to foreach name.en, name.fr, name.nl and display the name.fr if my locale == 'fr' and so on. All idea I have it's:

    <div v-if="locale == 'fr' "> {{ data.name.fr }} </div>
    <div v-if="locale == 'en' "> {{ data.name.en }} </div>  

and so on. May be there is some more effective way?


Solution

  • remember what you type in there is simply js. you could put the language on a variable on your data object and then use:

    data: {
      "lang": "en"
    }
    
    <div> {{ data.name[lang] }} </div>
    

    you could also re-structure your JSON response to look like this:

     data: {
      "lang": "en",
      "translations": {
        "en": {
          "configuration": "configuration",
          "description": "this is the configuration"
        },
        "fr": {
          "configuration": "configuration",
          "description": "c'est la configuration"
        },
        "nl": {
          "configuration": "configuratie",
          "description": "dit is de configuratie"
        }
      }
    }
    

    then you use in you template:

    <div> {{ translations[lang].configuration }}</div>
    

    this way the variable name in the template becomes more descriptive. you could also on change of language, take the whole object for a language and put it on data directly, so you do not have to refer to it via translations[lang] anymore.