[Vuejs]-Vue 3 vue-i18n. How to use $t(t) outside the app(.vue files)? Composition API

1๐Ÿ‘

I found a solution. Just import your i18n into a file outside the application and use i18n.global.t

import { createI18n } from "vue-i18n"

export const i18n = createI18n({
    legacy: false,
    locale: 'ja',
    fallbackLocale: 'en',
    messages,
})
import { i18n } from '@/i18n'

const { t: $t, d: $d, n: $n } = i18n.global

const expample = $t('some-text')

1๐Ÿ‘

I think your method should also be a composable so you can simply use the method useI18n() inside.

Something like

use-transform-datetime.ts

import { useI18n } from 'vue-i18n'

export const useTransformDatetime = () => {
  const { t } = useI18n()

  const transformDatetime = (config, value) => {
    if (value) {
      return $d(new Date(value), config)
    }
    return t('-')
  }

  return {
    transformDatetime
  }
}

then simply use it in your vue file who need it

<script setup>
   import { useTransformDatetime } from 'path-to-your-composables/use-transform-datetime'
   const { transformDatetime } = useTransformDatetime()
   console.log(transformDatetime(config, 'value'))
</script>

This way you can even add your others transform methods in the same composable

0๐Ÿ‘

Try to use of the useI18n composable function from vue-i18n to get the t method instead of $t:

<script setup>
   import { useI18n } from 'vue-i18n'
   const { t } = useI18n()
   console.log(t('greeting'))
</script>

Leave a comment