chore:中英文切换按钮能切换英文

This commit is contained in:
2026-01-15 15:10:46 +08:00
parent f7fcf7fb27
commit 1e6cd55f0a
2 changed files with 141 additions and 190 deletions

View File

@@ -1,205 +1,161 @@
import { langConfig } from './config-external.js'; import { langConfig } from './config-external.js';
// 缓存已加载的语言包 // 缓存已加载的语言包
const loadedLangPacks = {}; const loadedLangPacks = {};
// 处理页面目录映射 // 处理页面目录映射
function processRoutePath(route) { function processRoutePath(route) {
let routeParts = route.split("/"); let routeParts = route.split("/");
// ---- 处理页面目录映射 <begin> 分包造成的,需要根据实际目录结构进行映射---- // ---- 处理页面目录映射 <begin> 分包造成的,需要根据实际目录结构进行映射----
// 先处理特殊的分包路径 if (routeParts[0] === 'pages_tool') {
if (routeParts[0] === 'pages_tool') { routeParts = [routeParts[1], ...routeParts.slice(2)];
// pages_tool 分包下的页面,直接使用子目录作为语言包路径 } else if (routeParts[0] === 'pages_goods') {
routeParts = [routeParts[1], ...routeParts.slice(2)]; routeParts[0] = 'goods';
} else if (routeParts[0] === 'pages_goods') { } else if (routeParts[0] === 'pages_member') {
// pages_goods 分包映射到 goods 目录 routeParts[0] = 'member';
routeParts[0] = 'goods'; } else if (routeParts[0] === 'pages_order') {
} else if (routeParts[0] === 'pages_member') { routeParts[0] = 'order';
// pages_member 分包映射到 member 目录 } else if (routeParts[0] === 'pages_promotion') {
routeParts[0] = 'member'; const promotionModules = ['point', 'fenxiao', 'merch'];
} else if (routeParts[0] === 'pages_order') { if (routeParts[1] && promotionModules.includes(routeParts[1])) {
// pages_order 分包映射到 order 目录 routeParts = [routeParts[1], ...routeParts.slice(2)];
routeParts[0] = 'order'; }
} else if (routeParts[0] === 'pages_promotion') { }
// pages_promotion 分包特殊处理 // ---- 处理页面目录映射 <end>----
const promotionModules = ['point', 'fenxiao', 'merch'];
if (routeParts[1] && promotionModules.includes(routeParts[1])) { if (routeParts[0] === 'pages') {
routeParts = [routeParts[1], ...routeParts.slice(2)]; routeParts = routeParts.slice(1);
} }
}
// ---- 处理页面目录映射 <end>---- return routeParts.join("/");
// 去掉pages目录只保留子目录
if (routeParts[0] === 'pages') {
routeParts = routeParts.slice(1);
}
return routeParts.join("/");
} }
// 加载语言包(同步方式) // 加载语言包(同步方式)
function loadLangPackSync(lang, path) { function loadLangPackSync(lang, path) {
try { try {
if (loadedLangPacks[`${lang}_${path}`]) { if (loadedLangPacks[`${lang}_${path}`]) {
return loadedLangPacks[`${lang}_${path}`]; return loadedLangPacks[`${lang}_${path}`];
} }
const langData = require(`@/lang/${lang}/${path}.js`).lang; const langData = require(`@/lang/${lang}/${path}.js`).lang;
loadedLangPacks[`${lang}_${path}`] = langData; loadedLangPacks[`${lang}_${path}`] = langData;
return langData; return langData;
} catch (error) { } catch (error) {
console.error(`加载语言包 ${lang}/${path} 失败:`, error); console.error(`加载语言包 ${lang}/${path} 失败:`, error);
return {}; return {};
} }
} }
export default { export default {
langList: langConfig.langList, langList: langConfig.langList,
/** /**
* * 解析多语言 * 解析多语言
* @param {Object} field */
*/ lang(field) {
lang(field) { let _this = getCurrentPages()[getCurrentPages().length - 1];
let _this = getCurrentPages()[getCurrentPages().length - 1]; if (!_this) return;
if (!_this) return;
const locale = uni.getStorageSync('lang') || "zh-cn"; //设置语言 const locale = uni.getStorageSync('lang') || "zh-cn";
let value = ''; // 存放解析后的语言值 let value = '';
let langPath = ''; // 存放当前页面语言包路径 let langPath = '';
try { try {
//公共语言包(同步加载) var lang = loadLangPackSync(locale, 'common');
var lang = loadLangPackSync(locale, 'common');
let route = _this.route;
//当前页面语言包(同步加载) langPath = processRoutePath(route);
let route = _this.route;
langPath = processRoutePath(route); let currentPageLang = loadLangPackSync(locale, langPath);
// 加载当前页面语言包
let currentPageLang = loadLangPackSync(locale, langPath);
// 合并语言包 let mergedLang = { ...lang, ...currentPageLang };
let mergedLang = { ...lang, ...currentPageLang };
// 解析字段 var arr = field.split(".");
var arr = field.split("."); if (arr.length > 1) {
if (arr.length > 1) { let temp = mergedLang;
// 处理嵌套属性,如 common.currencySymbol let found = true;
let temp = mergedLang; for (let key of arr) {
let found = true; if (temp[key] !== undefined) {
for (let key of arr) { temp = temp[key];
if (temp[key] !== undefined) { } else {
temp = temp[key]; found = false;
} else { break;
found = false; }
break; }
} value = found ? temp : field;
} } else {
value = found ? temp : field; value = mergedLang[field] !== undefined ? mergedLang[field] : field;
} else { }
value = mergedLang[field] !== undefined ? mergedLang[field] : field;
} } catch (e) {
console.error('解析语言包失败:', e, { langPath, field, locale });
} catch (e) { value = field;
console.error('解析语言包失败:', e, { langPath, field, locale }); }
value = field;
}
if (arguments.length > 1) { if (arguments.length > 1) {
//有参数,需要替换 for (var i = 1; i < arguments.length; i++) {
for (var i = 1; i < arguments.length; i++) { value = value.replace("{" + (i - 1) + "}", arguments[i]);
value = value.replace("{" + (i - 1) + "}", arguments[i]); }
} }
} if (value == undefined || (value == 'title' && field == 'title')) value = '';
if (value == undefined || (value == 'title' && field == 'title')) value = ''; // field
// 多语言调试,注释后可以关闭控制台输出 if (field == value) {
if (field == value) { console.warn(`警告: 字段 ${field} 在语言包 ${langPath} 中未找到对应值,使用默认值 ${field} 当前语言: ${locale}`);
console.warn(`警告: 字段 ${field} 在语言包 ${langPath} 中未找到对应值,使用默认值 ${field} 当前语言: ${locale}`); }
}
return value; return value;
}, },
/** /**
* * 切换语言 * 切换语言
* @param {String} value 语言值 */
* @param {String} url 切换后跳转的页面url change(value, url = '/pages_tool/member/index') {
*/ let _this = getCurrentPages()[getCurrentPages().length - 1];
change(value, url = '/pages_tool/member/index') { if (!_this) return;
let _this = getCurrentPages()[getCurrentPages().length - 1];
if (!_this) return;
uni.setStorageSync("lang", value); uni.setStorageSync("lang", value);
const locale = uni.getStorageSync('lang') || "zh-cn"; //设置语言 const locale = uni.getStorageSync('lang') || "zh-cn";
// 清空已加载的语言包缓存 // ✅ 关键修复:清空所有语言包缓存(不再保留任何旧缓存)
for (let key in loadedLangPacks) { for (let key in loadedLangPacks) {
if (!key.startsWith(locale)) { delete loadedLangPacks[key];
delete loadedLangPacks[key]; }
}
}
this.refresh(); this.refresh();
if (url) { if (url) {
uni.reLaunch({ url: url }); uni.reLaunch({ url: url });
} }
}, },
//刷新标题、tabbar //刷新标题、tabbar
refresh() { refresh() {
let _this = getCurrentPages()[getCurrentPages().length - 1]; let _this = getCurrentPages()[getCurrentPages().length - 1];
if (!_this) return; if (!_this) return;
const locale = uni.getStorageSync('lang') || "zh-cn"; //设置语言 const locale = uni.getStorageSync('lang') || "zh-cn";
this.title(this.lang("title")); this.title(this.lang("title"));
},
//设置tabbar的文字语言 title(str) {
// uni.setTabBarItem({ if (str) {
// index: 0, uni.setNavigationBarTitle({
// text: this.lang("tabBar.home") title: str
// }); });
// uni.setTabBarItem({ }
// index: 1, },
// text: this.lang("tabBar.category") // 获取语言包列表
// }); list() {
// uni.setTabBarItem({ var list = [];
// index: 2, try {
// text: this.lang("tabBar.cart") for (var i = 0; i < langConfig.langList.length; i++) {
// }); let langType = langConfig.langList[i];
// uni.setTabBarItem({ let item = loadLangPackSync(langType, 'common');
// index: 3, list.push({
// text: this.lang("tabBar.member") name: item.common ? item.common.name : langType,
// }); value: langType
}, });
title(str) { }
if (str) { } catch (e) {
uni.setNavigationBarTitle({ console.error('获取语言包列表失败:', e);
title: str, }
success: function (res) { return list;
}, }
fail: function (err) { }
}
});
}
},
// 获取语言包列表
list() {
var list = [];
try {
//公共语言包
for (var i = 0; i < langConfig.langList.length; i++) {
let langType = langConfig.langList[i];
let item = loadLangPackSync(langType, 'common');
list.push({
name: item.common ? item.common.name : langType,
value: langType
});
}
} catch (e) {
console.error('获取语言包列表失败:', e);
}
return list;
}
}

View File

@@ -192,20 +192,15 @@ export default {
this.currentLangIndex = this.currentLangIndex === 0 ? 1 : 0; this.currentLangIndex = this.currentLangIndex === 0 ? 1 : 0;
const targetLang = this.langIndexMap[this.currentLangIndex]; const targetLang = this.langIndexMap[this.currentLangIndex];
uni.setStorageSync('lang', targetLang); // 调用语言切换逻辑(设置 storage + 清空缓存)
this.$langConfig.change(targetLang);
const pages = getCurrentPages();
if (pages.length === 0) return;
const currentPage = pages[pages.length - 1];
const route = currentPage.route;
console.log('【调试】切换语言:', targetLang, '路径:', route);
// H5 环境需要强制刷新页面才能生效
if (uni.getSystemInfoSync().platform === 'browser') { if (uni.getSystemInfoSync().platform === 'browser') {
window.location.reload(); // 延迟 100ms 确保 change() 执行完成
} else { setTimeout(() => {
uni.redirectTo({ url: `/${route}` }); window.location.reload();
}, 100);
} }
}, },
openKefuSelectPopup() { openKefuSelectPopup() {