Javascript Vue i18n中的TypeScript错误:“0”;财产'$t';不存在于类型';VueConstructor'&引用。我怎样才能修好它?
在项目中,一些常用函数位于单独的.ts文件中。 在这种情况下,我如何使用i18:Javascript Vue i18n中的TypeScript错误:“0”;财产'$t';不存在于类型';VueConstructor'&引用。我怎样才能修好它?,javascript,typescript,vue.js,vue-i18n,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> {
// 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 )
})()
//用于i18n
从“Vue”导入Vue
声明模块“vue/types/vue”{
接口VueConstructor{
$t:有吗
}
}
声明模块“vue/类型/选项”{
接口组件选项{
t?:有吗
}
}
(()=>{
常数测试=Vue.$t('auth.title');
console.log(测试)
})()
返回一个错误:
Property '$t' does not exist on type 'VueConstructor<Vue>"
类型“VueConstructor”上不存在属性“$t”
如何修复它?我们可以实现如下相同的效果 第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 { 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>
//首先将其导入到文件中
从'@/i18n'导入{translate,i18n};
//如果需要,我们可以在html中使用翻译
{{'sample text'| translate}}
//这就是我们如何在.ts或.vue文件中使用翻译的方法
//正常情况
testFunc(){
让test=`${translate('sample text')}`;
控制台日志(测试);
}
//在您的情况下,应该如下所示
(()=>{
const test=`${translate('auth.title')}`;
console.log(测试)
})()
我希望这将帮助您解决您的问题。我认为为了将translate函数用作过滤器,您需要添加:Vue.filter(“translate”,translate);