Documentation

The useTranslate composable

Not everything fits in a component. Attributes such as placeholder or title take a string, and sometimes you need a translation in your script. For these, use the useTranslate composable or the translate method.

The useTranslate composable

useTranslate returns a function, usually called t, that translates a string:

<script setup lang="ts">
import { useTranslate } from '@magic-translate/vue';
const t = useTranslate();
</script>
<template>
<input :placeholder="t('Search products')" />
</template>

t returns the original text while the translation loads. Once it is ready, the component re-renders. Like the <T> component, it accepts language and formality options:

<input :placeholder="t('Your name', { lang: 'fr', formality: 'formal' })" />

It also accepts an id, to edit this use of the text on its own:

<button :title="t('Save', { id: 'checkout-save' })" />

Variables

Pass values that should not be translated in v, and reference them as $name, the same as with the <T> component:

<input :placeholder="t('Search $count products', { v: { count } })" />

The text is translated once as Search {0} products, and the cached translation is reused when count changes.

useT is the same composable as useTranslate.

Translating in code

To translate a string in your script, call translate. It returns a promise.

import { useMagicTranslate } from '@magic-translate/vue';
const magicTranslate = useMagicTranslate();
const message = await magicTranslate.translate('Your order has been placed');
// with options
const formal = await magicTranslate.translate('How are you?', {
lang: 'fr',
formality: 'formal'
});

Without the lang option, the text is translated into the current language.

translate takes variables too:

const message = await magicTranslate.translate('Your order $id has shipped', {
v: { id: order.id }
});

Outside components, for example in a store, use the object returned by createMagicTranslate directly. It provides the same translate and setLanguage methods and language property.