Files
fe.ems.vue3/src/hooks/useI18n.ts
2023-12-28 09:25:03 +08:00

50 lines
1.1 KiB
TypeScript

import { computed, onBeforeMount } from 'vue';
import { useI18n } from 'vue-i18n';
import { localGet, localSet } from '@/utils/cache-local-utils';
import { CACHE_LOCAL_I18N } from '@/constants/cache-keys-constants';
export default function useLocale() {
//实例化i18n
const i18n = useI18n();
// 获取当前语言设置
const currentLocale = computed(() => {
return i18n.locale.value;
});
// 切换语言
const changeLocale = (value: string) => {
i18n.locale.value = value;
localSet(CACHE_LOCAL_I18N, value);
window.location.reload();
};
// 可选的语言
const optionsLocale = [
{
value: 'zh_CN',
label: '中文',
},
{
value: 'en_US',
label: 'English',
},
];
// 挂载前根据默认语言再设置一次
onBeforeMount(() => {
const localI18n = localGet(CACHE_LOCAL_I18N);
if (localI18n) {
i18n.locale.value = localI18n;
document.documentElement.lang = localI18n.replace('_', '-');
}
});
return {
optionsLocale,
currentLocale,
changeLocale,
t: i18n.t,
};
}