【问题标题】:Error in Vue i18n with TypeScript: "Property '$t' does not exist on type 'VueConstructor'. " . How can I fix it?带有 TypeScript 的 Vue i18n 中的错误:“类型 'VueConstructor' 上不存在属性 '$t'。”。我该如何解决?
【发布时间】:2019-09-15 14:28:11
【问题描述】:

在项目中,一些常用功能位于单独的 .ts 文件中。 在这种情况下我该如何使用 i18:

// for i18n
import  Vue  from 'vue'
declare module 'vue/types/vue' {
  interface VueConstructor  {
    $t: any
  }
}
declare module 'vue/types/options' {
  interface ComponentOptions<V extends Vue> {
    t?: any
  }
}

(()=>{
  const test = Vue.$t('auth.title');
  console.log( test )
})()

返回错误:

Property '$t' does not exist on type 'VueConstructor<Vue>"

我该如何解决?

【问题讨论】:

    标签: javascript typescript vue.js vue-i18n


    【解决方案1】:

    我们可以像下面这样实现同样的效果

    第 1 步:在 i18n 文件夹中创建一个单独的 index.ts 文件(您可以按照自己的方式进行操作 - 根级别或应用中的任何位置)

    i18n/index.ts

    import Vue from 'vue';
    import VueI18n from 'vue-i18n';
    
    // register i18n module
    Vue.use(VueI18n);
    
    const i18n = new VueI18n({
       locale: 'nb-NO', //if you need get the browser language use following "window.navigator.language"
       fallbackLocale: 'en',
       messages: {en, no},
       silentTranslationWarn: true
    })
    
    const translate = (key: string) => {
      if (!key) {
        return '';
      }
      return i18n.t(key);
    };
    
    export { i18n, translate}; //export above method
    

    第 2 步:确保在 main.ts 中使用(import)

    main.ts

    import { i18n } from '@/i18n';
    
    new Vue({ i18n, render: h => h(app) }).$mount('#app')
    

    经过上述配置后,我们应该可以在应用程序中的任何地方使用翻译

    第 3 步:如何在 .ts 和 .vue 文件中使用它

    // first import it into the file
    import { translate, i18n } from '@/i18n';
    
    //this is how we can use translation inside a html if we need
    <template>
      <h1>{{'sample text' | translate}}</h1>
    </template>
    
    //this is how we can use translation inside a .ts or .vue files
    <script lang='ts'>    
      //normal scenario
      testFunc(){
        let test = `${translate('sample text')}`;
        console.log(test );
      }
    
      //in your case it should be like below
      (()=>{
        const test = `${translate('auth.title')}`;
        console.log( test )
      })()
    </script>
    

    我希望这将帮助您解决问题。

    【讨论】:

    • 我认为为了使用 translate 函数作为过滤器,您需要添加:Vue.filter("translate", translate);
    猜你喜欢
    • 2019-07-16
    • 2018-01-15
    • 1970-01-01
    • 1970-01-01
    • 2019-03-07
    • 1970-01-01
    • 1970-01-01
    • 2023-02-21
    • 2019-10-10
    相关资源
    最近更新 更多