From 155c2588f7b6bbb7eea83338d1c56743b4ed51ce Mon Sep 17 00:00:00 2001 From: isaaczhao Date: Thu, 25 Apr 2024 16:18:14 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=AD=97=E7=AC=A6=E4=B8=B2=E6=A8=A1?= =?UTF-8?q?=E7=89=88=E6=94=AF=E6=8C=81key?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/locale/en.json | 1 + src/locale/index.ts | 22 ++++++++++++++++++++++ src/locale/zh-Hans.json | 1 + src/pages/index/i18n.vue | 6 +++++- 4 files changed, 29 insertions(+), 1 deletion(-) diff --git a/src/locale/en.json b/src/locale/en.json index 9362478..346638c 100644 --- a/src/locale/en.json +++ b/src/locale/en.json @@ -1,5 +1,6 @@ { "weight": "{heavy}KG", "weight2": "{0}KG", + "introduction": "I am {name},height:{detail.height},weight:{detail.weight}", "app.name": "En Title" } diff --git a/src/locale/index.ts b/src/locale/index.ts index 9169581..e3699d0 100644 --- a/src/locale/index.ts +++ b/src/locale/index.ts @@ -49,4 +49,26 @@ export function formatString(template: string, ...values: any) { return value !== undefined ? value : match }) } + +/** + * formatStr('我是{name},身高{detail.height},体重{detail.weight}',{name:'张三',detail:{height:178,weight:'75kg'}}) + * 暂不支持数组 + * @param template + * @param data + * @returns + */ +export function formatStr(template, data) { + const match = /\{(.*?)\}/g.exec(template) + if (match) { + const variableList = match[0].replace('{', '').replace('}', '').split('.') + let result = data + for (let i = 0; i < variableList.length; i++) { + result = result[variableList[i]] || '' + } + return formatStr(template.replace(match[0], result), data) + } else { + return template + } +} + export default i18n diff --git a/src/locale/zh-Hans.json b/src/locale/zh-Hans.json index 09d414c..5fa03f1 100644 --- a/src/locale/zh-Hans.json +++ b/src/locale/zh-Hans.json @@ -1,5 +1,6 @@ { "app.name": "中文标题", "weight": "{heavy}公斤", + "introduction": "我是 {name},身高:{detail.height},体重:{detail.weight}", "weight2": "{0}公斤" } diff --git a/src/pages/index/i18n.vue b/src/pages/index/i18n.vue index baa55b1..c526f0c 100644 --- a/src/pages/index/i18n.vue +++ b/src/pages/index/i18n.vue @@ -17,6 +17,9 @@ {{ $t('app.name') }} {{ $t('weight', { heavy: 100 }) }} {{ formatString(translate('weight2'), 100) }} + + {{ formatStr(translate('introduction'), user) }} + 切换语言 @@ -36,10 +39,11 @@