我们可以像下面这样实现同样的效果
第 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>
我希望这将帮助您解决问题。