Attempting to create a Vue application that supports two languages, utilizing local storage and store to store the selected language.
Initially, everything appears to be functioning correctly. After the user logs in, the default language is displayed in both components. Clicking on the second language triggers watchers in both components, updating the text accordingly. However, upon refreshing the page and selecting another language, only the navbar component switches languages, while the home component fails to update. Despite logging the chosen language in the setter, the watcher in the home component does not activate. The issue persists even after logging out, refreshing, and starting anew.
Store:
const localLanguage = localStorage.getItem('xx-user-language')
const state = () => ({
userLanguage: undefined,
});
const getters = {
getUserLanguage(state) {
if(localLanguage !== null && localLanguage !== undefined){
return localLanguage
}
return state.userLanguage;
},
};
const mutations = {
setUserLanguage(state, data) {
localStorage.setItem('xx-user-language', data)
console.log("setter " + data)
state.userLanguage = data;
},
};
Navbar Component:
HTML:
<div title="deutsch" class="icon-container">
<img @click="setLanguage('de')" src="german.png" alt="deutsch">
</div>
<div title="english" class="icon-container">
<img @click="setLanguage('en')" src=".english.png" alt="english">
</div>
JS:
computed:{
...mapGetters('language',{
getUserLanguage:"getUserLanguage"
})
},
watch:{
getUserLanguage: function(newValue){
this.setLanguage(newValue)
}
},
methods: {
setLanguage(lang){
this.setUserLanguage(lang)
this.text = text.navbar[lang]
},
...mapMutations('language',{
setUserLanguage:"setUserLanguage"
})
}
Home Component: JS:
computed: {
...mapGetters('language',{
getUserLanguage:"getUserLanguage"
})
},
watch: {
getUserLanguage: function(newValue){
console.log("home watcher" + newValue)
this.setLanguage(newValue)
}
},
methods: {
setLanguage(lang){
this.text = text.homepage[lang]
},
},