I'm developing an app in Vue using Vue Routers and Vue $i18n plugin.
This is my HTML:
<div class="locale-changer">
<select v-model="this.$i18n.locale" class="btn">
<option v-for="(lang, i) in langs" :key="`Lang${i}`" :value="lang">{{ lang }}</option>
</select>
</div>
And my JS:
export default {
name: "home",
data() {
return {
langs: ['Español', 'English'],
currentlang: this.$i18n.locale
}
},
mounted() {
if(localStorage.currentlang) this.currentlang = localStorage.currentlang;
},
watch: {
currentlang(newLang) {
localStorage.currentlang = newLang;
}
}
};
I have already searched the Internet but still cannot get it.
Hope you can help me! Thanks <3
I'm developing an app in Vue using Vue Routers and Vue $i18n plugin.
This is my HTML:
<div class="locale-changer">
<select v-model="this.$i18n.locale" class="btn">
<option v-for="(lang, i) in langs" :key="`Lang${i}`" :value="lang">{{ lang }}</option>
</select>
</div>
And my JS:
export default {
name: "home",
data() {
return {
langs: ['Español', 'English'],
currentlang: this.$i18n.locale
}
},
mounted() {
if(localStorage.currentlang) this.currentlang = localStorage.currentlang;
},
watch: {
currentlang(newLang) {
localStorage.currentlang = newLang;
}
}
};
I have already searched the Internet but still cannot get it.
Hope you can help me! Thanks <3
- Whats the question? – Code Spirit Commented Jul 16, 2020 at 13:19
- how to save the current language selected by the user in localstorage – NuzzeSicK Commented Jul 16, 2020 at 13:21
-
It's best practice to use
localStorage.setItem()
andlocalStorage.getItem()
for municating with localStorage. See MDN – StackByMe Commented Jul 16, 2020 at 13:22 -
BTW, you shouldn't use
this
in the template:<select v-model="this.$i18n.locale" class="btn">
should be<select v-model="$i18n.locale" class="btn">
– Tomer Commented Jul 16, 2020 at 13:37
2 Answers
Reset to default 1This is the syntax for saving in localStorage:
localStorage.setItem("name", value);
and to get and item:
localStorage.getItem("name")
see here: https://developer.mozilla/en-US/docs/Web/API/Window/localStorage
add @change event for setting the localStorage / sessionStorage and create mounted() function to load it at the beginning
<template>
<select @change="updateLanguage()" v-model="$i18n.locale">
<option v-for="(locale, i) in locales" :key="`locale-${i}`" :value="locale">
{{ locale.toUpperCase() }}
</option>
</select>
</template>
<script>
export default {
name: "LocaleSwitcher",
data() {
return { locales: ["sk", "cs", "en"] };
},
methods: {
updateLanguage() {
sessionStorage.setItem("locale", this.$i18n.locale);
},
},
mounted() {
if (sessionStorage.getItem("locale")) {
this.$i18n.locale = sessionStorage.getItem("locale");
} else {
sessionStorage.setItem("locale", this.$i18n.locale);
}
},
};
</script>