3

In normal context, we just attach translation property to a variable like :

this.name = this.$t('language.name');

But I want to specific it in a specific language sometime( ex: in French). Can we do something like this in vue.js ?

this.name = this.$t('language.name', locale: fr);
Debug Diva
  • 26,058
  • 13
  • 70
  • 123
DFX Nguyễn
  • 495
  • 5
  • 21

1 Answers1

4

Using the old package kazupon/vue-i18n, the following should be possible:

$t(key, locale)

When using the successor-package intlify/vue-i18n-next, the answer depends on if you are using Vue I18n's Legacy API or the newer Composition API:


Using Legacy API as described in the normal setup guide the usages of the t() function are stated here.

This means you can still use the following call to translate a key to a specific locale (e.g. 'fr'):

$t(key, locale)

Example:

$t('message.key', 'fr')

Using the Composition API by calling createI18n() with the option legacy: false (as described here), the usages of the t() function are different as stated here. You can no longer pass the locale-string as the second parameter, but the locale can be handed over inside a TranslateOptions object. Unfortunately, there is no t(key,TranslateOptions) variant, but only the following variants:

$t(key, plural, TranslateOptions)
$t(key, defaultMsg, TranslateOptions)
$t(key, interpolations, TranslateOptions)

So the easiest solution would be e.g.:

$t('message.key', 1, { locale: 'fr' })
codeflorist
  • 334
  • 3
  • 11
  • Thank you for helping me, it worked. Can you share me documents or anything related to this topic? – DFX Nguyễn Dec 03 '21 at 03:31
  • 1
    @DFXNguyễn No problem! I've actually realised, that there are two modes of usage for Vue I18n: the Legacy API and the newer Composition API. I assume you are using the latter one. I've updated my answer to state solutions for both modes and added links to the documentation. – codeflorist Dec 04 '21 at 22:38