Ski*_*kif 7 javascript typescript vue.js vue-i18n
在项目中,一些常用函数位于单独的 .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 )
})()
Run Code Online (Sandbox Code Playgroud)
返回错误:
Property '$t' does not exist on type 'VueConstructor<Vue>"
Run Code Online (Sandbox Code Playgroud)
我该如何修复它?
小智 4
我们可以实现如下所示的相同效果
第 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
Run Code Online (Sandbox Code Playgroud)
第 2 步:确保在 main.ts 中使用上面的(导入)
主要.ts
import { i18n } from '@/i18n';
new Vue({ i18n, render: h => h(app) }).$mount('#app')
Run Code Online (Sandbox Code Playgroud)
经过上述配置后,我们应该能够在应用程序中任何我们想要的地方使用翻译
第 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>
Run Code Online (Sandbox Code Playgroud)
我希望这将帮助您解决您的问题。
| 归档时间: |
|
| 查看次数: |
19868 次 |
| 最近记录: |