refine: i18n

This commit is contained in:
菲鸽 2024-05-04 10:59:10 +08:00
parent 5849176b59
commit 188554bf04
3 changed files with 9 additions and 9 deletions

View File

@ -51,21 +51,21 @@ export function formatString(template: string, ...values: any) {
}
/**
* formatStr('我是{name},身高{detail.height},体重{detail.weight}',{name:'张三',detail:{height:178,weight:'75kg'}})
* formatI18n('我是{name},身高{detail.height},体重{detail.weight}',{name:'张三',detail:{height:178,weight:'75kg'}})
*
* @param template
* @param data
* @param template eg: `我是{name}`
* @param obj key与多语言字符串对应eg: `{name:'菲鸽'}`
* @returns
*/
export function formatStr(template, data) {
export function formatI18n(template, obj) {
const match = /\{(.*?)\}/g.exec(template)
if (match) {
const variableList = match[0].replace('{', '').replace('}', '').split('.')
let result = data
let result = obj
for (let i = 0; i < variableList.length; i++) {
result = result[variableList[i]] || ''
}
return formatStr(template.replace(match[0], result), data)
return formatI18n(template.replace(match[0], result), obj)
} else {
return template
}

View File

@ -1,5 +1,5 @@
{
"name": "unibest",
"name": "unibest-base",
"appid": "H57F2ACE4",
"description": "",
"versionName": "1.0.0",

View File

@ -18,7 +18,7 @@
<view class="m-4">{{ $t('weight', { heavy: 100 }) }}</view>
<view class="m-4">{{ formatString(translate('weight2'), 100) }}</view>
<view class="m-4">
{{ formatStr(translate('introduction'), user) }}
{{ formatI18n(translate('introduction'), user) }}
</view>
<view class="text-green-500 mt-12">切换语言</view>
@ -39,7 +39,7 @@
</template>
<script lang="ts" setup>
import i18n, { formatStr, formatString, translate } from '@/locale/index'
import i18n, { formatI18n, formatString, translate } from '@/locale/index'
import { testI18n } from '@/utils/i18n'
const current = ref(uni.getLocale())