congming_huose-apk/common/i18n/index.js

80 lines
1.8 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 多语言配置
import en from './en.js';
import zh from './zh.js';
import ja from './ja.js';
import ru from './ru.js';
import { reconnectUserWsForLanguage } from '@/common/utils/appUserWs.js';
// 语言配置对象
const messages = {
en,
zh,
ja,
ru
};
// 创建一个响应式的语言状态
let currentLanguage = uni.getStorageSync('language') || 'en';
// 获取当前语言
function getCurrentLanguage() {
return currentLanguage;
}
// 设置语言
function setLanguage(lang) {
if (lang === currentLanguage) {
return;
}
console.log('设置语言:', lang);
currentLanguage = lang;
uni.setStorageSync('language', lang);
// 长连接 query 的 lang 随 storage下一拍再建连避免与旧 socket 的 onClose 竞态、并确保 storage 已落盘
setTimeout(() => {
try {
reconnectUserWsForLanguage();
} catch (e) {
console.warn('[i18n] 切换语言后重连长连接失败', e);
}
}, 0);
// 触发语言变化事件
uni.$emit('languageChanged', lang);
// 强制更新所有页面组件
const pages = getCurrentPages();
pages.forEach(page => {
if (page.$vm && page.$vm.$forceUpdate) {
page.$vm.$forceUpdate()
}
})
// 触发全局更新
if (typeof uni.$vm !== 'undefined' && uni.$vm.$forceUpdate) {
uni.$vm.$forceUpdate();
}
}
// 获取翻译文本
function t(key) {
const langMessages = messages[currentLanguage] || messages.zh;
return langMessages[key] || key;
}
// 获取所有支持的语言
function getSupportedLanguages() {
return [
{ code: 'en', name: 'English' },
{ code: 'zh', name: '中文' },
{ code: 'ja', name: '日本語' },
{ code: 'ru', name: 'Русский' }
];
}
export default {
messages,
getCurrentLanguage,
setLanguage,
t,
getSupportedLanguages
};