Home » vue » Global method this.$t from vue-i18n does not work in function

Global method this.$t from vue-i18n does not work in function

Posted by: admin November 26, 2021 Leave a comment

Questions:

I define vue-I18n globally:

Vue.use(VueI18n);
export default new VueI18n({
  locale: process.env.VUE_APP_I18N_LOCALE || 'cs',
  fallbackLocale: process.env.VUE_APP_I18N_FALLBACK_LOCALE || 'cs',
  messages: loadLocaleMessages(),
});

I can use it anywhere with:

this.$t('sign-up.something-went-wrong')

But not inside a for each loop, probably because new anonymous class is created. How can I reference it from there?

function convertErrors(jsonErrors) {
  const veeErrors = {};
  console.log(this.$t('sign-up.heading'));
  return veeErrors;
}

And called from export.default

methods: {
  async submitForm() {
    try {
      const { data } = await this.$store.dispatch('CREATE_USER_PROFILE', {
        email: this.email,
        password: this.password,
        nickname: this.nickname,
      });

      if (!this.personalData) {
        this.success = true;
        return true;
      }

      if (data.token === undefined) {
        this.error = this.$t('sign-up.something-went-wrong');
        return false;
      }

      const jwtData = jwtDecode(data.token);
      const vehicles = [];
      setVehicles.call(this, vehicles);
      await this.$store.dispatch('UPDATE_USER_PROFILE', {
        jwt: data,
        userId: jwtData.userId,
      });
      this.success = true;
    } catch (error) {
      this.success = false;
      if (error.response) {
        console.log(this.$t('sign-up.something-went-wrong')); // this works
        const veeErrors = convertErrors(error.response.data); // this fails
        this.$refs.form.setErrors(veeErrors);
      } else {
        this.error = this.$t('sign-up.something-went-wrong');
      }
    }
    return this.success;
  },
},

I can see the following error in the chrome console:

vue.runtime.esm.js?2b0e:619 [Vue warn]: Error in v-on handler (Promise/async): "TypeError: Cannot read property '$t' of undefined"

And

TypeError: Cannot read property '$t' of undefined
at convertErrors (SignUpForm.vue?9fa9:236)
at VueComponent._callee$ (SignUpForm.vue?9fa9:321)
at tryCatch (runtime.js?96cf:45)
Answers:

convertErrors has no “this”, it’s not bound to a component. Move it into the component’s methods in order to reference this:

methods: {
  convertErrors(jsonErrors) {
    const veeErrors = {};
    console.log(this.$t('sign-up.heading'));
    return veeErrors;
  }
}

OR

use call in order to set the context (the this) inside convertErrors:

const veeErrors = convertErrors.call(this, error.response.data);

###

You can store VueComponent before for each loop. Like this one:

let self = this
// .......
jsonErrors.errors.forEach((error) => {
  if (error.field) {
    veeErrors.$field = [self.$t(error.messageKey)];
  } else {
    self.error = self.$t(error.messageKey);
  }
});