Vuex state doesn't updated between Vue instances

Viewed 59

I have 3 different Vue instances that are using the same store but when I change the value of 'language' from the one instance, the others doesn't be updated

<script>
  import { mapState } from 'vuex';
  import store from '@common/store/'

  export default {
    methods: {
      setLocale(lang) {
        store.dispatch('setLanguage', lang)
      },
    },
    computed: {
      ...mapState({
        language: state => state.language.language,
      }),
    },
  }
</script>
language/index.js
export default {

    state: {
        language: __language,
    },
    getters: {

        getLanguage: state => () => {
            return state.language
        },
    },
    actions: {
        setLanguage({ commit }, lang) {
            commit('setLanguage', lang);
        },
    },
    mutations: {
        setLanguage(state, lang) {
            state.language = lang;
        },
    },
};
import Vue from 'vue';
import App from './App';
import i18n from "@common/i18n";
import store from '@common/store/'
import { mapState } from "vuex";

new Vue({
    store,
    i18n,
    render: h => h(App),
    computed: {
        ...mapState({
            language: state => {
                i18n.locale = state.language.language
                return state.language.language
            },
        }),
    }
}).$mount('#menu');

first instance which I made the state change

second instache which is not updated

1 Answers

I would implement 2 corrections : use the helper mapGetters instead of mapState. Cf doc

Then, in your mutation, use this.$set

setLanguage(state, lang) {
   this.$set(state, 'language', lang)
},
Related