2024-01-29 14:48:07 +08:00
|
|
|
|
import { createI18n } from 'vue-i18n'
|
|
|
|
|
|
|
|
|
|
import en from './en.json'
|
|
|
|
|
import zh from './zh.json'
|
|
|
|
|
|
|
|
|
|
const messages = {
|
|
|
|
|
en,
|
|
|
|
|
zh,
|
|
|
|
|
}
|
|
|
|
|
console.log(uni.getLocale())
|
|
|
|
|
|
2024-01-29 19:14:01 +08:00
|
|
|
|
export const getLocale = () => {
|
2024-01-29 16:59:12 +08:00
|
|
|
|
const browserLang = uni.getLocale()
|
|
|
|
|
if (Object.keys(messages).includes(browserLang)) {
|
|
|
|
|
return browserLang
|
|
|
|
|
}
|
|
|
|
|
return 'zh' // fallback language, 可以配置,必须是 message 的key
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
console.log(getLocale())
|
|
|
|
|
|
2024-01-29 14:48:07 +08:00
|
|
|
|
const i18n = createI18n({
|
2024-01-29 16:59:12 +08:00
|
|
|
|
locale: getLocale(), //
|
2024-01-29 14:48:07 +08:00
|
|
|
|
messages,
|
|
|
|
|
})
|
|
|
|
|
|
2024-01-29 16:59:12 +08:00
|
|
|
|
/**
|
|
|
|
|
* 非 vue 文件使用这个方法
|
|
|
|
|
* @param { string } localeKey 多语言的key,eg: "app.name"
|
|
|
|
|
*/
|
|
|
|
|
export const translate = (localeKey: string) => {
|
2024-01-29 18:59:17 +08:00
|
|
|
|
if (!localeKey) {
|
|
|
|
|
console.error(`[i18n] Function translate(), localeKey param is required`)
|
|
|
|
|
return ''
|
|
|
|
|
}
|
2024-01-29 16:59:12 +08:00
|
|
|
|
const locale = getLocale()
|
|
|
|
|
const message = messages[locale]
|
|
|
|
|
if (Object.keys(message).includes(localeKey)) {
|
|
|
|
|
return message[localeKey]
|
|
|
|
|
}
|
|
|
|
|
return localeKey
|
|
|
|
|
}
|
2024-01-29 14:48:07 +08:00
|
|
|
|
export default i18n
|