perf(i18n): 使用 t 函数

This commit is contained in:
菲鸽 2024-06-16 16:28:08 +08:00
parent 3c2d52e060
commit 236d002c7c
3 changed files with 36 additions and 43 deletions

View File

@ -17,59 +17,55 @@ console.log(uni.getLocale())
console.log(i18n.global.locale) console.log(i18n.global.locale)
/** /**
* vue 使 * vue 使
* @param { string } localeKey keyeg: "app.name" * @param { string } key keyeg: "app.name"
* @returns {string} eg: "{heavy}KG"
*/ */
export const translate = (localeKey: string) => { export const getTemplateByKey = (key: string) => {
if (!localeKey) { if (!key) {
console.error(`[i18n] Function translate(), localeKey param is required`) console.error(`[i18n] Function getTemplateByKey(), key param is required`)
return '' return ''
} }
const locale = uni.getLocale() const locale = uni.getLocale()
console.log('locale:', locale) console.log('locale:', locale)
const message = messages[locale] const message = messages[locale] // 拿到某个多语言的所有模板(是一个对象)
if (Object.keys(message).includes(localeKey)) { if (Object.keys(message).includes(key)) {
return message[localeKey] return message[key]
} }
return localeKey console.error(`[i18n] Function getTemplateByKey(), key param ${key} is not existed.`)
} return ''
/**
* formatString('已阅读并同意{0}和{1}','用户协议','隐私政策') ->
* @deprecated 使 formatI18n使key而不是索引
* @param template
* @param values
* @returns
*/
export function formatString(template: string, ...values: any) {
console.log(template, values)
// 使用map来替换{0}, {1}, ...等占位符
return template.replace(/{(\d+)}/g, (match, index) => {
const value = values[index]
return value !== undefined ? value : match
})
} }
/** /**
* formatI18n('我是{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 eg: `我是{name}` * @param template eg: `我是{name}`
* @param obj key与多语言字符串对应eg: `{name:'菲鸽'}` * @param {Object|undefined} data key与多语言字符串对应eg: `{name:'菲鸽'}`
* @returns * @returns
*/ */
export function formatI18n(template, obj) { function formatI18n(template: string, data?: any) {
const match = /\{(.*?)\}/g.exec(template) return template.replace(/\{([^}]+)\}/g, function (match, key: string) {
if (match) { // console.log( match, key) // => { detail.height } detail.height
const variableList = match[0].replace('{', '').replace('}', '').split('.') const arr = key.trim().split('.')
let result = obj let result = data
for (let i = 0; i < variableList.length; i++) { while (arr.length) {
result = result[variableList[i]] || '' const first = arr.shift()
} result = result[first]
return formatI18n(template.replace(match[0], result), obj)
} else {
return template
} }
return result
})
} }
/**
* t('introduction',{name:'张三',detail:{height:178,weight:'75kg'}})
* t('introduction',{name:'张三',detail:{height:178,weight:'75kg'}})
*
* @param template eg: `我是{name}`
* @param {Object|undefined} obj key与多语言字符串对应eg: `{name:'菲鸽'}`
* @returns
*/
export function t(key, obj?) {
return formatI18n(getTemplateByKey(key), obj)
}
export default i18n export default i18n

View File

@ -22,10 +22,7 @@
<view class="text-green-500">多语言测试</view> <view class="text-green-500">多语言测试</view>
<view class="m-4">{{ $t('app.name') }}</view> <view class="m-4">{{ $t('app.name') }}</view>
<view class="m-4">{{ $t('weight', { heavy: 100 }) }}</view> <view class="m-4">{{ $t('weight', { heavy: 100 }) }}</view>
<view class="m-4">{{ formatString(translate('detail'), 175, 60) }}</view> <view class="m-4">{{ t('introduction', user) }}</view>
<view class="m-4">
{{ formatI18n(translate('introduction'), user) }}
</view>
<view class="text-green-500 mt-12">切换语言</view> <view class="text-green-500 mt-12">切换语言</view>
<view class="uni-list"> <view class="uni-list">
@ -45,7 +42,7 @@
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
import i18n, { formatI18n, formatString, translate } from '@/locale/index' import i18n, { t } from '@/locale/index'
import { testI18n } from '@/utils/i18n' import { testI18n } from '@/utils/i18n'
const current = ref(uni.getLocale()) const current = ref(uni.getLocale())

View File

@ -1,4 +1,4 @@
import { translate as t } from '@/locale/index' import { t } from '@/locale/index'
/** 非vue 文件使用 i18n */ /** 非vue 文件使用 i18n */
export const testI18n = () => { export const testI18n = () => {