Vue i18n TypeError: Cannot read property '_t' of undefined

3.9k views Asked by At

I try to use vue-i18n in ts file of a component like this:

export default class MyComponent extends Vue {
  readonly i18nTitle = this.$t('translation.key');

  //...
}

But I get the error:

TypeError: Cannot read property '_t' of undefined stackoverflow

This error only occurs when I try to use i18n in the ts file but it works fine when I use it in the html.

My configuration of i18n is really basic:

// i18n/index.ts
import Vue from 'vue';
import VueI18n from 'vue-i18n';
import fr from './translations/fr.json';

Vue.use(VueI18n);

export const i18n = new VueI18n({
  locale: 'fr',
  fallbackLocale: 'fr',
  messages: {
    fr,
  },
});

// maint.ts
import { i18n } from './i18n';

new Vue({
  el: '#app',
  i18n,
  components: { App },
  template: '<App/>',
});

Any idea what I am missing?

1

There are 1 answers

1
Baboo On BEST ANSWER

After playing a bit I saw that it can work if I use a getter.

This is how I translate texts from the ts file:

export default class MyComponent extends Vue {
  get i18n() {
    return {
      title: this.$t('translation.key');
    };
  }
}

And use it in the html like this:

<h1>{{i18n.title}}</h1>