Search code examples
vue.jsinternationalizationvuexvue-routervue-i18n

Overriding store.js with key from locale.json


I need to dynamically pass the data from current locale to an array in store.js. the array looks like this:

skills: [
      {
        id: "1",
        type: "hard",
        title: "Technical Skills",
        mastery: "low",
      },
        ]
});

And so I need to replace this title: "Technical skills", with the data from locale json file.

So if I do like this: store.js:

import en from "../src/locales/en.json";
import fr from "../src/locales/fr.json";
import it from "../src/locales/it.json";
skills: [
      {
        id: "1",
        type: "hard",
        title: `${en.hardSkills.TechnicalSkills}`,
        mastery: "low",
      },
export { store };

It does kinda work. And if I change en with fr or it it will change the displayed language. But of course I need to change languages from the website and not from the code.

Perhaps it has to be something like this:

title: `${$i18n.locale.hardSkills.TechnicalSkills}`,

But in this case $i18n is not defined.

I can't figure it out

the object in locales/fr.json

"hardSkills" : {
  "TechnicalSkills" : "Compétences techniques"
}

and locales/it.json

"hardSkills" : {
  "TechnicalSkills" : "Abilità tecniche"
}

and of course locales/en.json

"hardSkills" : {
  "TechnicalSkills" : "Technical skills"
}

Solution

  • Alright it's done. Here's the solution.

    store.js:

    skills: [
         {
           id: "1",
           type: "hard",    
         },
         {
           id: "2",
           type: "hard",        
         },
    

    fr.json: //just keep the structure, it's the same for any other language.

     "hardSkills": {
        "Technical skills":  "Compétences techniques",
        "Computer skills": "Compétences informatiques",
    }
    

    *.vue

       <v-col
                  v-for="hardSkill in hardSkills"
                  :key="hardSkill.id"
                  cols="auto"
                  
                >
                  {{ $t(`hardSkills.${hardSkill.title}`) }}
                
       </v-col>