Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to persist localisation in a vue app?

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 ?

like image 228
codeDragon Avatar asked Oct 24 '25 16:10

codeDragon


1 Answers

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"
}
like image 73
sulu00 Avatar answered Oct 27 '25 00:10

sulu00



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!