language.ts 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import { nextTick } from 'vue'
  2. class Language {
  3. private i18n: any;
  4. private loadLocale: Array<string> = []; //已加载的语言
  5. public file: string = '';
  6. constructor(i18n: any) {
  7. this.i18n = i18n
  8. }
  9. /**
  10. *
  11. * @param locale 设置语言
  12. */
  13. public setI18nLanguage(locale: string) {
  14. if (this.i18n.mode === 'legacy') {
  15. this.i18n.global.locale = locale
  16. } else {
  17. this.i18n.global.locale = locale
  18. }
  19. let html = document.querySelector('html')
  20. html && html.setAttribute('lang', locale)
  21. }
  22. /**
  23. * 加载语言包
  24. * @param path
  25. * @param locale
  26. * @returns
  27. */
  28. public async loadLocaleMessages(app: string, path: string, locale: string) {
  29. try {
  30. const file = path == '/' ? 'index' : path.replace('/', '').replaceAll('/', '.')
  31. if (this.loadLocale.includes(`${app}/${locale}/${file}`)) {
  32. return nextTick()
  33. }
  34. this.loadLocale.push(`${app}/${locale}/${file}`)
  35. if (app != 'app' && !this.loadLocale.includes(`${app}/${locale}/pages`)) {
  36. const pagesMessages = await import(`~/addon/${app}/lang/${locale}/pages.json`)
  37. this.i18n.global.mergeLocaleMessage(locale, pagesMessages)
  38. this.loadLocale.push(`${app}/${locale}/pages`)
  39. }
  40. // 引入语言包文件
  41. const messages = await import(app == 'app' ? `~/app/lang/${locale}/${file}.json` : `~/addon/${app}/lang/${locale}/${file}.json`)
  42. const prefix = this.getFileKey(app, path)
  43. let data: Record<string, string> = {}
  44. Object.keys(messages.default).forEach(key => {
  45. data[`${prefix}.${key}`] = messages.default[key]
  46. })
  47. this.i18n.global.mergeLocaleMessage(locale, data)
  48. this.setI18nLanguage(locale)
  49. return nextTick()
  50. } catch {
  51. this.setI18nLanguage(locale)
  52. return nextTick()
  53. }
  54. }
  55. /**
  56. * @param app
  57. * @param path
  58. */
  59. public getFileKey = (app: string, path: string) => {
  60. const file = path == '/' ? 'index' : path.replace('/', '').replaceAll('/', '.')
  61. return `${app}.${file}`
  62. }
  63. }
  64. export default Language