关于vue-i18n国际化 不能将类型“TranslateRes

2024-07-24  本文已影响0人  不是坂本

关于vue-i18n国际化的注意点

在vue中如何使用vue-81in处理国际化此处不赘叙,记录下遇到的异常抛错。

注意点一:使用报错

在单独的文件中引入时,报错

//src/i18n/index.ts
import Vue from 'vue'
import VueI18n from 'vue-i18n'
import utils from './../utils/utils'

import en from './en'
import zh from './zh'

Vue.use(VueI18n)  //会把$t挂到Vue.prototype上,以便在.vue文件中使用this.$t()

// 国际化
const i18n = new VueI18n({
    locale: utils.getCookie('language') || 'zh',// set locale
    messages: {
        zh: zh, // 中文语言包
        en: en // 英文语言包
    }
})

export default i18n
//ts文件引入
import { t } from '@/i18n'

const title = t('title')
console.log(title)

出现异常提示:Cannot read properties of undefined (reading '_t')


Image.png

改为:

import i18n from '@/i18n'

const title = i18n.t('title')
console.log(title)

注意点二:ts类型

不能将类型“TranslateResult”分配给类型“string”。
不能将类型“LocaleMessages”分配给类型“string”。

如:

private title: string = this.$t(’common.title‘)

提示以上的ts问题。

此时需要覆写i18n的ts类型。对应github也有相应的工单 :https://github.com/kazupon/vue-i18n/issues/410

添加ts声明

// src/vue-i18n.d.ts
 import VueI18n from 'vue-i18n/types'

/**

 * Overloads VueI18n interface to avoid needing to cast return value to string.

 * @see [https://github.com/kazupon/vue-i18n/issues/410](https://github.com/kazupon/vue-i18n/issues/410)

 */

declare module 'vue-i18n/types' {

  export default class VueI18n {

    t(key: Path, locale: Locale, values?: Values): string;

    t(key: Path, values?: Values): string;

  }

}

declare module 'vue/types/vue' {

  interface Vue {

    $t: typeof VueI18n.prototype.t;

  }

  interface VueConstructor<V extends Vue = Vue> {

    i18n: typeof VueI18n.prototype;

  }

}

export {}

题外话

这阵子接触到前端项目需要国际化的专项开发,在已有的已上线多年的多个项目中无疑是个工作量庞大的挑战,这就更加需要依赖自动化工具来帮我们省下大量不必要的人力开销和时间成本。
此处推荐一个自动国际化工具:前端自动国际化解决方案
从基本面已经解决70%的工作成本,如果不满足自己的需求也可以fork后再进行二创定制化开发,比如改写为使用 recast 保留原始代码的格式等。同时也非常感谢这位开源工具的大佬。

上一篇 下一篇

猜你喜欢

热点阅读