3

I am trying to build a multilingual Vue app with vue-i18n, and I am wondering how to persist the selected language? Anybody has experience with localisation? Is it possible by adding the language as a param to vue router? And or are there other ways ?

codeDragon
  • 35
  • 3

1 Answers1

4

Each time you change/set the locale you need to store its value in the localStorage. Add this to your App:

watch: {
    '$i18n.locale': function(newVal, oldVal) {
        localStorage.setItem('last-locale', newVal)
     }
}

Then in the i18n.js initialization file read this value on startup:

export default createI18n({
  ...
  locale: getStartingLocale(),
  ...
})

And just add a function:

function getStartingLocale() {
    if (localStorage.getItem('last-locale')) {
        return localStorage.getItem('last-locale')
    }
    return process.env.VUE_APP_I18N_LOCALE || "en"
}
sulu00
  • 92
  • 1
  • 6