index.ts 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import { createI18n } from 'vue-i18n'
  2. import en from './en.json'
  3. import zhHans from './zh-Hans.json' // 简体中文
  4. const messages = {
  5. en,
  6. 'zh-Hans': zhHans, // key 不能乱写,查看截图 screenshots/i18n.png
  7. }
  8. const i18n = createI18n({
  9. locale: uni.getLocale(), // 获取已设置的语言,fallback 语言需要再 manifest.config.ts 中设置
  10. messages,
  11. allowComposition: true,
  12. })
  13. /**
  14. * 可以拿到原始的语言模板,非 vue 文件使用这个方法,
  15. * @param { string } key 多语言的key,eg: "app.name"
  16. * @returns {string} 返回原始的多语言模板,eg: "{heavy}KG"
  17. */
  18. export const getTemplateByKey = (key: string) => {
  19. if (!key) {
  20. console.error(`[i18n] Function getTemplateByKey(), key param is required`)
  21. return ''
  22. }
  23. const locale = uni.getLocale()
  24. const message = messages[locale] // 拿到某个多语言的所有模板(是一个对象)
  25. if (Object.keys(message).includes(key)) {
  26. return message[key]
  27. }
  28. try {
  29. const keyList = key.split('.')
  30. return keyList.reduce((pre, cur) => {
  31. return pre[cur]
  32. }, message)
  33. } catch (error) {
  34. console.error(`[i18n] Function getTemplateByKey(), key param ${key} is not existed.`)
  35. return ''
  36. }
  37. }
  38. /**
  39. * formatI18n('我是{name},身高{detail.height},体重{detail.weight}',{name:'张三',detail:{height:178,weight:'75kg'}})
  40. * 暂不支持数组
  41. * @param template 多语言模板字符串,eg: `我是{name}`
  42. * @param {Object|undefined} data 需要传递的数据对象,里面的key与多语言字符串对应,eg: `{name:'菲鸽'}`
  43. * @returns
  44. */
  45. function formatI18n(template: string, data?: any) {
  46. return template.replace(/\{([^}]+)\}/g, function (match, key: string) {
  47. // console.log( match, key) // => { detail.height } detail.height
  48. const arr = key.trim().split('.')
  49. let result = data
  50. while (arr.length) {
  51. const first = arr.shift()
  52. result = result[first]
  53. }
  54. return result
  55. })
  56. }
  57. /**
  58. * t('introduction',{name:'张三',detail:{height:178,weight:'75kg'}})
  59. * => formatI18n('我是{name},身高{detail.height},体重{detail.weight}',{name:'张三',detail:{height:178,weight:'75kg'}})
  60. * 没有key的,可以不传 data;暂不支持数组
  61. * @param template 多语言模板字符串,eg: `我是{name}`
  62. * @param {Object|undefined} data 需要传递的数据对象,里面的key与多语言字符串对应,eg: `{name:'菲鸽'}`
  63. * @returns
  64. */
  65. export function t(key, data?) {
  66. return formatI18n(getTemplateByKey(key), data)
  67. }
  68. export default i18n