[Vuejs]-Setting "starter" values on created() with Vuex

0👍

Found the problem – was not returning the value of navigator.language in my getter

👤S Said

0👍

Found some problems in example:

  • function defaultLagn not returning
  • acess store without this.$store in component

here a example running: https://codepen.io/ptcmariano/pen/jQZmWW

const mapGetters = Vuex.mapGetters;
const mapActions = Vuex.mapActions;
const mapState = Vuex.mapState;

const store = new Vuex.Store({
    state: {
          userData: {
            prefLang: "UNDEF"
            // some other data..
          }
    },
    getters: {
        defaultLang: () => { return navigator.language.slice(0,2) }
    },
    actions: {
        setDefaultLang({ state, getters }) {
            state.userData.prefLang = getters.defaultLang
        }
    }
});


new Vue({
    el: "#app",
    store: store,
    template: `<div class="chat-display"> <p> lang: {{ this.userData.prefLang }}</p> </div>`,
    created() {
        this.$store.dispatch('setDefaultLang')
    },
    computed: {
        ...mapGetters([
            'defaultLang'
        ]),
        ...mapState([
            'userData'
        ])
    },
    methods: {
        ...mapActions([
            'setDefaultLang'
        ])
    }
});
#app

Leave a comment