I'm trying to implement a locale update using Vue, Vuex and VueI18n. I thought i found the way to update the locale setting the i18n value in the store object and then using it like this (mutation):
UPDATE_LANGUAGE: (state, newLanguage) => {
state.language = newLanguage;
this.$i18n.locale = state.language;
}
But surprisingly doesn't work... it says this.$i18n is not defined, but it is.
import store from "./store";
import EnMessages from "@/messages/en.json";
import EsMessages from "@/messages/es.json";
const i18n = new VueI18n(Vue, {
es: EsMessages,
en: EnMessages
});
i18n.locale = store.state.language;
store.$i18n = i18n;
Vue.http.interceptors.push((request, next) => {
//internacionalizacion en todas las urls
request.url = `${request.url}?lang=${store.getters["getLanguage"]}`;
//token en todas las urls
request.headers.set("token", store.getters["getToken"]);
next();
});
new Vue({
i18n,
router,
store,
render: h => h(App)
}).$mount("#app");
Change your method declaration to:
UPDATE_LANGUAGE: function(state, newLanguage) {
state.language = newLanguage;
this.$i18n.locale = state.language;
}
Here is why:
You're declaring a new method inside a Vue component. If you are using the function
keyword to declare the method then this
will refer to the owner of the function, in this case the Vue component instance (which is what you want).
Using an arrow function on the other hand this
does not refer to the owner of the function but this
is taken from its context. You get an error that this
doesn't exist there - and if it did it probably wouldn't be your Vue component.