You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

68 lines
1.4 KiB

import { get } from 'lodash-es'
import zh from './languages/zh.json'
import en from './languages/en.json'
import { reactive } from 'vue'
const Languages = {
zh: zh,
en: en
}
export type LanguagesType = keyof typeof Languages
const LocaleState = reactive<{
locale: LanguagesType
}>({
locale: 'zh'
})
type FlattenObject<T, Prefix extends string = ''> = T extends object
? {
[K in keyof T & (string | number)]: FlattenObject<
T[K],
Prefix extends '' ? `${K}` : `${Prefix}.${K}`
>
}[keyof T & (string | number)]
: Prefix
type FlattenKeys<T> = FlattenObject<T>
type TranslationKey = FlattenKeys<typeof zh>
function useLocale() {
function setLocale(locale: LanguagesType) {
LocaleState.locale = locale
}
function getLocale(): string {
return LocaleState.locale
}
function t(key: TranslationKey, replacements?: Record<string, string>): string {
let text: string =
LocaleState.locale in Languages
? get(Languages[LocaleState.locale], key)
: get(Languages['zh'], key)
if (!text) {
text = get(Languages['zh'], key)
if (!text) {
return key
}
}
if (replacements) {
Object.entries(replacements).forEach(([key, value]) => {
text = text.replace(new RegExp(`{${key}}`, 'g'), value)
})
}
return text
}
return {
setLocale,
getLocale,
t
}
}
export { useLocale }