關(guān)于vue-i18n國際化的注意點(diǎn)
在vue中如何使用vue-81in處理國際化此處不贅敘,記錄下遇到的異常拋錯(cuò)宪塔。
注意點(diǎn)一:使用報(bào)錯(cuò)
在單獨(dú)的文件中引入時(shí)磁奖,報(bào)錯(cuò)
//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)
出現(xiàn)異常提示:Cannot read properties of undefined (reading '_t')
改為:
import i18n from '@/i18n'
const title = i18n.t('title')
console.log(title)
注意點(diǎn)二:ts類型
不能將類型“TranslateResult”分配給類型“string”某筐。
不能將類型“LocaleMessages”分配給類型“string”比搭。
如:
private title: string = this.$t(’common.title‘)
提示以上的ts問題。
此時(shí)需要覆寫i18n的ts類型南誊。對應(yīng)github也有相應(yīng)的工單 :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 {}
題外話
這陣子接觸到前端項(xiàng)目需要國際化的專項(xiàng)開發(fā)身诺,在已有的已上線多年的多個(gè)項(xiàng)目中無疑是個(gè)工作量龐大的挑戰(zhàn),這就更加需要依賴自動(dòng)化工具來幫我們省下大量不必要的人力開銷和時(shí)間成本弟疆。
此處推薦一個(gè)自動(dòng)國際化工具:前端自動(dòng)國際化解決方案
從基本面已經(jīng)解決70%的工作成本戚长,如果不滿足自己的需求也可以fork后再進(jìn)行二創(chuàng)定制化開發(fā),比如改寫為使用 recast 保留原始代碼的格式等怠苔。同時(shí)也非常感謝這位開源工具的大佬同廉。