import { createI18n } from 'vue-i18n'; import { localST_Locale } from './base/storage'; import { LANGUAGE_ENGLISH, LANGUAGE_CHINESE } from './base/variables'; import { useLocaleStore } from './base/store/use-locale'; import ajax from './base/ajax'; /** * 多语言解决方案 * @see https://vue-i18n.intlify.dev/ */ let i18n = null; // 创建一个函数来加载语言文件 async function loadLocaleMessages() { const messages = {}; const locales = [LANGUAGE_ENGLISH, LANGUAGE_CHINESE]; // 根据你的需求添加语言代码 for (const locale of locales) { const url = `/i18n/lang-${locale}.json`; const response = await ajax.get(url); messages[locale] = response; } return messages; } /** * 检查一个字符串是否是合法的语言名称 * @param {string} lang * @returns */ function isValidLanguage(lang) { return lang === LANGUAGE_ENGLISH || lang === LANGUAGE_CHINESE; } /** * 设置当前的语言 * @param {string} locale - en/zh */ export function setI18nLanguage(locale) { const is_valid = isValidLanguage(locale); if (!is_valid) { return; } if (!i18n) { return; } i18n.global.locale = locale; localST_Locale.setItem(locale); /** * NOTE: * If you need to specify the language setting for headers, such as the `fetch` API, set it here. * The following is an example for axios. * * axios.defaults.headers.common['Accept-Language'] = locale */ document.querySelector('html').setAttribute('lang', locale); const store = useLocaleStore(); store.updateLanguage(locale); } export async function setupI18n() { const messages = await loadLocaleMessages(); i18n = createI18n({ locale: LANGUAGE_CHINESE, fallbackLocale: LANGUAGE_ENGLISH, messages }); return i18n; }