来自 vue-i18n 的全局方法 this.$t 在函数中不起作用

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

我全局定义了vue-I18n:

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(),
});

我可以在任何地方使用它:

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

但不是在 for each 循环中,可能是因为创建了新的匿名 class。我如何从那里引用它?

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

并从 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;
  },
},

我可以在 chrome 控制台中看到以下错误:

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

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)

您可以在每个循环之前存储 VueComponent。喜欢这个:

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

convertErrors 没有 "this",它没有绑定到组件。将其移动到组件的 methods 以引用 this:

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

使用 call 以在 convertErrors:

中设置上下文 (this)
const veeErrors = convertErrors.call(this, error.response.data);