Composables
useTranslation
Description
The useTranslation composable provides a wrapper around the Nuxt i18n translation function, with enhanced support for debugging translation keys and optional fallback strings. It conditionally displays raw translation keys based on a query parameter, making it useful for localization audits and development environments.
FEATURE GOALS
- Provide a consistent and customizable way to handle translations.
- Allow display of raw translation keys via URL query for debugging.
- Suppress non-critical i18n warnings to reduce console noise.
FEATURE EXPECTATIONS
- Returns the translated string using Nuxt’s
$i18n.t()method. - Displays the key itself if
showTranlsationKeys=trueis present in the URL query. - Suppresses translation warnings (e.g., missing, fallback, silent).
DEV STRATEGIES
- Composables Logic
const greeting = useTranslation('home.welcome', 'Welcome!');
- Returns a translated message or a fallback if missing.
- If ?showTranlsationKeys=true is present in the URL, it will return "home.welcome" directly.
- Implementation
export const useTranslation = (key: string, default_string?: string) => {
const nuxtApp = useNuxtApp();
const route = useRoute();
if (route && route.query && route.query.showTranlsationKeys === 'true') {
return key;
}
return nuxtApp.$i18n.t(key, default_string, {
missingWarn: false,
silentTranslationWarn: true,
fallbackWarn: false,
});
};
- Integrates with Nuxt app context and current route.
- Provides translation with suppressible warnings.
- DEFAULT BEHAVIOR
| Feature | Default | Description |
|---|---|---|
key | required | Translation key from i18n resources. |
default_string | optional | Fallback string if translation is missing. |
showTranlsationKeys | false | If query param is true, returns the raw key instead of the translation. |
missingWarn | false | Disables warning for missing translation keys.. |
silentTranslationWarn | true | Silences translation warnings entirely. |
fallbackWarn | false | Suppresses fallback-related warnings. |
FLOW SUMMARY
- Reads the route query to determine whether to show translation keys.
- If showTranlsationKeys=true, returns the raw key to aid in debugging.
- Otherwise, returns the translated string (or a fallback) via $i18n.t().
- Suppresses i18n-related warnings for cleaner developer experience.