83 lines
2.2 KiB
JavaScript
83 lines
2.2 KiB
JavaScript
import { createI18n } from 'vue-i18n'
|
||
import zh from './zh.json'
|
||
import en from './en.json'
|
||
import ar from './ar.json'
|
||
import tr from './tr.json'
|
||
import bn from './bn.json'
|
||
|
||
// 语言包
|
||
const messages = { en, ar, zh, tr, bn }
|
||
|
||
// 默认语言配置
|
||
const defaultLocale = 'en'
|
||
const defaultDirection = 'ltr'
|
||
|
||
// 创建 i18n 实例(使用默认值)
|
||
const i18n = createI18n({
|
||
legacy: false,
|
||
locale: defaultLocale, // 使用默认值,稍后更新
|
||
fallbackLocale: defaultLocale,
|
||
messages,
|
||
})
|
||
|
||
// 设置文档方向
|
||
export const setDocumentDirection = (lang) => {
|
||
// 定义语言方向映射
|
||
const languages = {
|
||
en: 'ltr',
|
||
// zh: 'ltr',
|
||
ar: 'rtl',
|
||
tr: 'ltr',
|
||
bn: 'ltr',
|
||
}
|
||
|
||
const direction = languages[lang] || 'ltr'
|
||
document.documentElement.setAttribute('dir', direction)
|
||
document.documentElement.setAttribute('lang', lang)
|
||
}
|
||
|
||
// 初始化 i18n(在 Pinia 可用后调用)
|
||
export const initI18n = (langStore) => {
|
||
try {
|
||
// 设置初始语言
|
||
if (langStore.selectedLang) {
|
||
i18n.global.locale.value = langStore.selectedLang.type
|
||
setDocumentDirection(langStore.selectedLang.type)
|
||
}
|
||
|
||
// 监听语言变化
|
||
langStore.$subscribe((mutation, state) => {
|
||
if (state.selectedLang) {
|
||
i18n.global.locale.value = state.selectedLang.type
|
||
setDocumentDirection(state.selectedLang.type)
|
||
}
|
||
})
|
||
|
||
console.log('i18n initialized with language:', langStore.selectedLang?.type)
|
||
} catch (error) {
|
||
console.warn('Failed to initialize i18n with store, using defaults:', error)
|
||
setDocumentDirection(defaultDirection)
|
||
}
|
||
}
|
||
|
||
// 切换语言函数
|
||
export const setLocale = (langStore, langType) => {
|
||
try {
|
||
const language = langStore.langList.find((item) => item.type === langType)
|
||
|
||
if (language) {
|
||
langStore.setLanguage(language)
|
||
console.log(`Language changed to: ${language.value}`)
|
||
} else {
|
||
console.warn(`Language ${langType} is not supported`)
|
||
}
|
||
} catch (error) {
|
||
console.warn('Store not available when setting locale:', error)
|
||
// 即使 store 不可用,也更新 i18n
|
||
i18n.global.locale.value = langType
|
||
setDocumentDirection(langType === 'ar' ? 'rtl' : 'ltr')
|
||
}
|
||
}
|
||
|
||
export default i18n
|