Home > Mobile >  Vue 3 vue-i18n. How to use $t(t) outside the app(.vue files)? Composition API
Vue 3 vue-i18n. How to use $t(t) outside the app(.vue files)? Composition API

Time:01-07

I want to format my date-time outside the component.

function transformDatetime(config, value) {
    if (value) {
        return $d(new Date(value), config);
    }
    return $t('-');
}

I'm trying to get $t from the App instance. But it only works in the context of the component, just like useI18n.

import { getCurrentInstance } from 'vue'

export default function useGlobal() {
    const instance = getCurrentInstance()
    if (!instance) return
    return instance.appContext.config.globalProperties
}

CodePudding user response:

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')

CodePudding user response:

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>

CodePudding user response:

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

  • Related