useI18n.ts 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import { i18n } from '@/plugins/vueI18n'
  2. type I18nGlobalTranslation = {
  3. (key: string): string
  4. (key: string, locale: string): string
  5. (key: string, locale: string, list: unknown[]): string
  6. (key: string, locale: string, named: Record<string, unknown>): string
  7. (key: string, list: unknown[]): string
  8. (key: string, named: Record<string, unknown>): string
  9. }
  10. type I18nTranslationRestParameters = [string, any]
  11. const getKey = (namespace: string | undefined, key: string) => {
  12. if (!namespace) {
  13. return key
  14. }
  15. if (key.startsWith(namespace)) {
  16. return key
  17. }
  18. return `${namespace}.${key}`
  19. }
  20. export const useI18n = (
  21. namespace?: string
  22. ): {
  23. t: I18nGlobalTranslation
  24. } => {
  25. const normalFn = {
  26. t: (key: string) => {
  27. return getKey(namespace, key)
  28. }
  29. }
  30. if (!i18n) {
  31. return normalFn
  32. }
  33. const { t, ...methods } = i18n.global
  34. const tFn: I18nGlobalTranslation = (key: string, ...arg: any[]) => {
  35. if (!key) return ''
  36. if (!key.includes('.') && !namespace) return key
  37. //@ts-ignore
  38. return t(getKey(namespace, key), ...(arg as I18nTranslationRestParameters))
  39. }
  40. return {
  41. ...methods,
  42. t: tFn
  43. }
  44. }
  45. export const t = (key: string) => key