From b0b03a30e4edc01bfa48296ebadf16e89e3def52 Mon Sep 17 00:00:00 2001 From: xiaoxian521 <1923740402@qq.com> Date: Tue, 18 Jul 2023 16:16:55 +0800 Subject: [PATCH] =?UTF-8?q?perf:=20=E4=BC=98=E5=8C=96`transformI18n`?= =?UTF-8?q?=E5=87=BD=E6=95=B0=EF=BC=8C=E5=9B=BD=E9=99=85=E5=8C=96=E6=94=AF?= =?UTF-8?q?=E6=8C=81=E6=97=A0=E9=99=90=E5=B5=8C=E5=A5=97=E7=BA=A7=E5=88=AB?= =?UTF-8?q?=EF=BC=88=E5=BD=93=E7=84=B6=E5=B9=B3=E5=8F=B0=E8=BF=98=E6=98=AF?= =?UTF-8?q?=E6=8E=A8=E8=8D=90=E5=B5=8C=E5=A5=97=E5=B1=82=E7=BA=A7=E8=B6=8A?= =?UTF-8?q?=E5=B0=91=E8=B6=8A=E5=A5=BD=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/plugins/i18n.ts | 31 ++++++++++++++++++++++++++++--- 1 file changed, 28 insertions(+), 3 deletions(-) diff --git a/src/plugins/i18n.ts b/src/plugins/i18n.ts index 98fa6b803..ec53256b9 100644 --- a/src/plugins/i18n.ts +++ b/src/plugins/i18n.ts @@ -1,8 +1,8 @@ // 多组件库的国际化和本地项目国际化兼容 import { App, WritableComputedRef } from "vue"; -import { storageLocal } from "@pureadmin/utils"; import { type I18n, createI18n } from "vue-i18n"; import { responsiveStorageNameSpace } from "@/config"; +import { storageLocal, isObject } from "@pureadmin/utils"; // element-plus国际化 import enLocale from "element-plus/lib/locale/lang/en"; @@ -30,6 +30,30 @@ export const localesConfigs = { } }; +/** 获取对象中所有嵌套对象的key键,并将它们用点号分割组成字符串 */ +function getObjectKeys(obj) { + const stack = []; + const keys = []; + + stack.push({ obj, key: "" }); + + while (stack.length > 0) { + const { obj, key } = stack.pop(); + + for (const k in obj) { + const newKey = key ? `${key}.${k}` : k; + + if (obj[k] && isObject(obj[k])) { + stack.push({ obj: obj[k], key: newKey }); + } else { + keys.push(newKey); + } + } + } + + return keys; +} + /** * 国际化转换工具函数(自动读取根目录locales文件夹下文件进行国际化匹配) * @param message message @@ -47,8 +71,9 @@ export function transformI18n(message: any = "") { return message[locale?.value]; } - const key = message.match(/(\S*)\./)?.[1]; - if (key && Object.keys(siphonI18n("zh-CN")).includes(key)) { + const key = message.match(/(\S*)\./)?.input; + + if (key && getObjectKeys(siphonI18n("zh-CN")).find(item => item === key)) { return i18n.global.t.call(i18n.global.locale, message); } else if (!key && Object.keys(siphonI18n("zh-CN")).includes(message)) { // 兼容非嵌套形式的国际化写法