2

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.

enter image description here enter image description here Any thoughts??

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");
txomin
  • 177
  • 2
  • 3
  • 15
  • 1
    Try changing the method definition to: `UPDATE_LANGUAGE: function(state, newLanguage) {` – andypotato Sep 02 '19 at 00:17
  • it worked, but, i don't understand why... arrow function in es6 is supposed to keep the this of the whole object but not the traditional function()[]. Isn't this that way?? You can put it as an answer and i'll check it. – txomin Sep 02 '19 at 19:16
  • Please see my answer below - I tried to explain it a bit more in detail. – andypotato Sep 02 '19 at 23:47
  • _"arrow function in es6 is supposed to keep the this of the whole object "_ that's not correct. The `this` for an arrow function is the context of where it is defined. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#No_separate_this – Phil Sep 02 '19 at 23:55

1 Answers1

1

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.

andypotato
  • 703
  • 5
  • 10
  • You can also use the shorter function syntax `UPDATE_LANGUAGE (state, newLanguage) { ... }` which is the equivalent of what you have without using the `function` keyword – Phil Sep 02 '19 at 23:57