【问题标题】:Vue i18n TypeError: Cannot read property '_t' of undefinedVue i18n TypeError:无法读取未定义的属性“_t”
【发布时间】:2020-10-16 19:35:06
【问题描述】:

我尝试在这样的组件的ts 文件中使用vue-i18n

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

  //...
}

但我得到了错误:

TypeError: 无法读取未定义堆栈溢出的属性“_t”

仅当我尝试在ts 文件中使用i18n 时才会出现此错误,但当我在html 中使用它时它工作正常。

i18n的配置真的很基础:

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

知道我错过了什么吗?

【问题讨论】:

    标签: vue.js vue-i18n


    【解决方案1】:

    玩了一会儿,我发现如果我使用 getter 就可以工作。

    这就是我翻译 ts 文件中的文本的方式:

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

    并像这样在html 中使用它:

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

    【讨论】:

    • 这是正确的解决方案,因为使用计算属性将确保在更改语言时自动更新翻译。
    猜你喜欢
    • 1970-01-01
    • 2020-01-14
    • 2020-11-18
    • 2022-06-28
    • 2020-10-09
    • 2021-12-14
    • 2020-10-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多