Home > Mobile >  Vue 3 watch not working after refresh page
Vue 3 watch not working after refresh page

Time:11-03

I m trying to make a vue application available in 2 languages, I m using localstorage and store to save the chosen language.

Everything seems to work perfect, after the user just logged in the default language is shown in both components, when i click on the second language both components watchers are active and would react and update the text. However when i refresh the page, and i click on the another language it only changes on the navbar component and not on the home component, when i console log on the setter i get the chosen language but the watcher on the home component isnt triggering. When i logout and refresh and start everything again it works until i refresh. What m i missing here?

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" >
              <img @click="setLanguage('de')" src="german.png" alt="deutsch">
            </div>
            <div title="english" >
              <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]
    },
  },

CodePudding user response:

Your Vuex getter is wrong. It must be like this:

const state = () => ({
  userLanguage: localStorage.getItem('xx-user-language'),
});

const getters = {
  getUserLanguage(state) {
    return state.userLanguage;
  },
};
  • Related