Search code examples
javascriptpythonvue.jsinternationalizationvue-i18n

How to force translate i18n in some specific text (variable) in Vuejs


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

Solution

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