国际化
实现方式
借助 vue-i18n 和@intlify/unplugin-vue-i18n 这款 vite 插件配合来实现国际化,国际化文件可以采用 yaml 或 json 等格式。
创建 i18n.ts 用于支撑相关功能:
typescript
import { type I18n, createI18n } from 'vue-i18n'
import { invoke } from '@vintage-gis/core'
function siphonI18n(prefix = 'zh-CN') {
const tmp: Map<string, any> = new Map()
const entries = Object.entries(
import.meta.glob('../../locales/*.y(a)?ml', { eager: true })
).map(([key, value]: any) => {
const matched = key.match(/([A-Za-z0-9-_]+)\./i)[1]
if (tmp.has(matched)) {
return [matched, Object.assign(tmp.get(matched), value.default)]
} else {
tmp.set(matched, Object.assign({}, value.default))
return [matched, value.default]
}
})
tmp.clear()
return Object.fromEntries(entries)[prefix]
}
const localesConfigs = {
zh: {
...siphonI18n('zh-CN')
},
en: {
...siphonI18n('en')
}
}
// 指定英文 无视浏览器选项
const fixedLocale = 'en'
export const i18n: I18n = createI18n({
globalInjection: true,
legacy: false, // 设置为 false,启用 composition API 模式
locale: navigator.language, // (默认英文语言) 'zh-CN', 'en' navigator.language
fallbackLocale: 'en',
messages: localesConfigs
})
/**
* .ts 中使用此函数!
* 此函数可以配合i18n Ally插件来进行国际化智能提示
* @param key 要翻译的key
* @returns
*/
export const $t = (key: string) => {
return invoke(i18n.global.t, key, localesConfigs) as string
}
// 获取当前浏览器的语言
export const getLang = (): string => navigator.language.toLowerCase()
// 是否是英文语言
export const isEn = (): boolean =>
fixedLocale ? fixedLocale === 'en' : getLang().indexOf('en') > -1
// 是否是中文语言
export const isZh = (): boolean =>
fixedLocale ? fixedLocale !== 'en' : getLang().indexOf('zh') > -1在main.ts中使用它:
app.use(i18n)vue 组件中使用
可以使用 $t 获取国际化值:
html
<div>
<p>{{ $t('buttons.login') }}</p>
</div>TIP
VsCode 中推荐安装 lokalise.i18n-ally 插件,可以有更好的提示效果