Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading