index.ts 2.6 KB

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