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 ?
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"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With